As we know, node.js is a single thread. The code will run in this sequence.
- Initialize program
- Top level code get executed
- require modules
- then event callbacks started
- finally the event loop will do it’s work
Note: When there are heavy tasks then event loop send those to thread pool.
Thread pool
- There are additional 4 threads or more.
- It handle expensive (heavy) tasks like compression, cryptography, etc.
Avoid blocking the event loop
- Avoid using sync versions of functions in fs, crypto, zlib modules in the callback functions.
- Avoid complex calculations for example – loop inside loop.
const fs = require("fs"); const crypto = require("crypto"); const startTime = Date.now(); process.env.UV_THREADPOOL_SIZE = 4; setTimeout(() => console.log("1st setTimeout"), 0); setImmediate(() => console.log("1st setImmediate")); fs.readFile("test-file.txt", () => { console.log("Abhishek"); console.log("**************"); setTimeout(() => console.log("2nd setTimeout"), 0); setTimeout(() => console.log("3rd setTimeout"), 3000); setImmediate(() => console.log("2nd setImmediate")); process.nextTick(() => console.log("Process.nextTick")); crypto.pbkdf2("password", "salt", 100000, 1024, "sha512", () => { console.log(Date.now() - startTime, "Password encrypted"); }); crypto.pbkdf2("password", "salt", 100000, 1024, "sha512", () => { console.log(Date.now() - startTime, "Password encrypted"); }); crypto.pbkdf2("password", "salt", 100000, 1024, "sha512", () => { console.log(Date.now() - startTime, "Password encrypted"); }); crypto.pbkdf2("password", "salt", 100000, 1024, "sha512", () => { console.log(Date.now() - startTime, "Password encrypted"); }); }); console.log("Top level code");
Output: