← Main page

Node.js concepts

Main components

  1. JavaScript is run in a single thread with V8 engine.
  2. I/O is implemented with libuv library.
  3. C++ addons for low-level operations like compression or encryption.

Difference between network and file I/O

  1. Network I/O uses operating system notification mechanisms.
  2. 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.

  1. Timers: executes callbacks scheduled with setTimeout and setInterval.
  2. Pending callbacks: executes callbacks deferred to the next iteration (due to a limit of calls).
  3. Idle, prepare: used internally.
  4. Poll: retrieves new I/O events and execute all I/O callbacks (except socket closing).
  5. Check: executes callbacks scheduled with setImmediate. Useful in I/O callbacks to run something right after poll phase was finished.
  6. 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:

  1. Code
  2. Call stack
  3. 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:

  1. New space. Usually from 1 to 8 Mb. Garbage collection is performed frequently here.
  2. 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.

Additional information