NodeJS Event Loop: a lean concept review
Daniel Domingueti
Tech lead | Backend software engineer | Java | NodeJS | Fintechs
Summary:
1. Introduction
NodeJS is a single-threaded language. That is, only one task is executed at a time.
Efficiency is not a problem at all given the event loop approach, which we’re going to take a look today.
First of all, let’s review two important concepts:
2. Heap and stack memory
Heap: Memory space to storage objects and dynamic data.
Stack (LIFO): Memory space that refers to function calls and primary variables.
function example() {
let x = 10; // Stack
let object = { valor: 20 }; // Heap
}
exemplo(); // Referred in stack
3. How does event loop actually work?
It manages async operations and keep a non-blocking behavior.
It interacts with the “Call Stack”, “Callback queue”, “Microtask queue” and "Node API".
领英推荐
4. Practical example
console.log("1");
setTimeout(() => {
console.log("2");
}, 0);
Promise.resolve().then(() => console.log("3"));
console.log("4");
5. Related problems
Stack overflow: occurs when recursive functions grows non-stop, filling up the call stack, which blocks the execution.
function nonStopRecursive() {
return nonStopRecursive(); // Never stops, fills up the Call Stack
}
nonStopRecursive();
Memory leak: occurs when object references are not released.
let list = [];
setInterval(() => {
list.push(new Array(1000000).fill("leak")); // Never releases the memory.
}, 1000);
Blocking code: once Node is single-threaded, long synchronous operations blocks the event loop execution, which blocks other the execution of other tasks.
const fs = require("fs");
// Reads a large file in a blocking approach
const data = fs.readFileSync("large_file.txt");
console.log("File loaded"); // NodeJS blocks until the file is read.
6. Conclusion
At the end of the day, event loop is a core mechanism behind the asynchronous and non-blocking NodeJS architecture.
This is what makes the application efficient and allows you to run parallel operations (even though it's not truly multi-thread).
Understanding its behavior is crucial to avoid issues such as Stack Overflow, Memory Leaks and Blocking Code. Not only that, but it's also important to remember the processing priority between the Microtask and Callback queues.
I highly recommend watching: https://www.youtube.com/watch?v=8aGhZQkoFbQ