Node.js concepts
Main components
- JavaScript is run in a single thread with V8 engine.
- I/O is implemented with libuv library.
- C++ addons for low-level operations like compression or encryption.
Difference between network and file I/O
- Network I/O uses operating system notification mechanisms.
- Thread pool is used for file I/O because file operations are blocking in libuv. Libuv developers decided to simplify file I/O implementation.
process.env.UV_THREADPOOL_SIZE
is used to set number of threads in the pool. By default the thread pool has 4 threads. The threadpool is also used for compression and encryption.
Event loop
Event loop consists of several phases. Each phase has a FIFO queue of callbacks. Phase is finished when either all callback were called or when a sertain limit of calls was reached.
- Timers: executes callbacks scheduled with setTimeout and setInterval.
- Pending callbacks: executes callbacks deferred to the next iteration (due to a limit of calls).
- Idle, prepare: used internally.
- Poll: retrieves new I/O events and execute all I/O callbacks (except socket closing).
- Check: executes callbacks scheduled with setImmediate. Useful in I/O callbacks to run something right after poll phase was finished.
- Close callbacks: socket close callbacks. https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/
process.nextTick
nextTick callback is executed right after current operation finishes before other callbacks in a queue. In this sense setImmediate should be called nextTick.
Memory
Node.js memory consists of:
- Code
- Call stack
- Heap
By default, memory limit is 1.4 Gb (different versions of Node have different limits). --max-old-space-size
allows to change the limit.
Garbage collector
Heap separated into two spaces:
- New space. Usually from 1 to 8 Mb. Garbage collection is performed frequently here.
- Old space. Garbage collection is rare here.
Cluster mode
Cluster mode is a mode when the main process is forked as many times as we need (usually equals to the number of cores).
Forked processes reuse the same port of an HTTP server.