Node.js itself is not single-threaded.
Node.js developers often confuse the main single-threaded event loop with Node.js entirely.
When a Node.js app is running, it automatically creates 4 threads under the worker pool for blocking tasks.
So at any given time, there are at least five threads.
This worker pool is managed by Libuv.
The blocking tasks are mainly I/O-bound and CPU-intensive.
I/O bound
a. DNS: dns.lookup(), dns.lookupService()
b. File system except fs.FSWatcher()CPU-intensive tasks
a. Some crypto methods such as crypto.pbkdf2(), crypto.scrypt(), crypto.randomBytes(), crypto.randomFill(), crypto.generateKeyPair()
b. All zlib APIs other than those using libuv thread pool synchronously.
The main thread/event loop works for JavaScript execution as usual, but the worker pool takes care of blocking tasks for the main loop.
So, Node.js shouldn't be confused.
Thanks for reading.
I do a deep dive into foundational concepts & how things work under the hood. You can consider connecting with or following me, Ali Raza, here and on LinkedIn to get along with the journey.
Top comments (0)