Event loop and thread pool in Node.js

  • Post category:Node
  • Reading time:2 mins read

As we know, node.js is a single thread. The code will run in this sequence.

  1. Initialize program
  2. Top level code get executed
  3. require modules
  4. then event callbacks started
  5. 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:

event loop and thread pool in node

Share this