What is Node.js and why is it called single-threaded?
Quick answer
Node.js is a JavaScript runtime built on Chrome's V8 engine that runs your JavaScript on a single main thread and uses non-blocking I/O, so one thread can handle many concurrent connections.
Your JavaScript code runs on one thread, so there is no shared-memory race condition between your own functions. But Node.js is not single-threaded overall: the libuv library handles network I/O through the operating system's asynchronous mechanisms and uses a thread pool (four threads by default) for file system access, DNS lookups, compression and some crypto functions.
When a request arrives and needs a database result, Node starts the operation, registers a callback and moves on to other work instead of waiting. This model is excellent for I/O-heavy applications such as APIs, chat and streaming, and poor for long CPU-bound computation on the main thread, which blocks every other request.
Key points
- Your JavaScript runs on one thread
- libuv uses the OS and a thread pool for I/O
- Great for I/O-bound work, risky for CPU-bound work