What is the Event Loop?
Node.js is single-threaded but handles thousands of concurrent connections thanks to its event loop architecture.
The Call
Stack
hljs js
function first() {
second();
console.log('first');
}
function second() {
console.log('second');
}
first();
// Output: second,
first
Async with Promises
hljs js
async function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await
response.json();
return data;
}
fetchData().then(data => console.log(data));
Never Block the Event Loop
hljs js
// BAD - blocks the event loop
const
result = fs.readFileSync('large-file.txt');
// GOOD - non-blocking
const result = await fs.promises.readFile('large-file.txt');
Using Worker Threads for CPU
Tasks
hljs js
const { Worker } = require('worker_threads');
const worker = new Worker('./heavy-computation.js');
worker.on('message', result =>
console.log(result));
Offload CPU-intensive work to worker threads to keep the event loop free.
