What is Node.js and why is it called single-threaded?
- Technology:
- Node.js
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.
Detailed explanation
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.
How to explain it in an interview
Node.js is a JavaScript runtime built on V8 with an event loop and libuv for I/O. Your JavaScript runs on one thread, but file, network and DNS work is handed to the operating system or a small thread pool, and the callbacks come back through the event loop. That makes Node very efficient for I/O-heavy servers, while CPU-heavy work needs worker threads or a separate service.
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
Common mistakes
- Saying Node.js is completely single-threaded. Only the JavaScript execution is; libuv uses a thread pool for some I/O and crypto work.
- Running CPU-heavy loops, synchronous file calls or large JSON parsing on the request path, which blocks every other request.