Event loop, streams, workers, memory, performance
Practise these as flashcards. One or two lines each; the ones you miss come back first.
Start freeThe main phases are timers, pending callbacks, idle/prepare, poll, check, and close callbacks. Each phase processes specific types of events, such as timer callbacks or I/O events.
The event loop is blocked by long-running synchronous code, like heavy computations or infinite loops. This prevents other events from being processed and can make the application unresponsive.
Back-pressure is a mechanism that prevents writable streams from being overwhelmed by pausing the readable stream when the writable stream can't keep up. It helps manage memory and ensures efficient data flow.
I use environment variables, often with the dotenv package, to load configuration from a .env file. This keeps settings separate from code and allows secure management of secrets.
The libuv thread pool handles expensive asynchronous operations, like file system or crypto tasks, outside the main event loop. This allows Node.js to remain non-blocking and responsive even when performing heavy I/O.
I use profiling tools like clinic.js or node --prof to measure event loop latency. Monitoring response times and using process._getActiveRequests() can also help identify blocking code.
Worker threads run JavaScript in multiple threads and share memory, clusters spawn multiple Node.js processes for scaling servers, and child processes execute external scripts. Each is suited for different concurrency and isolation needs.
I avoid retaining unnecessary references, use weak references when appropriate, and regularly profile memory usage. Heap snapshots taken with Chrome DevTools or node --inspect help identify leaks.
package-lock.json locks dependency versions, ensuring consistent installs across environments. It prevents accidental upgrades and helps with reproducible builds.
I use process.on('unhandledRejection', handler) to log and handle rejections globally. In production, I prefer to fail fast or shut down gracefully if critical errors occur.
I listen for termination signals like SIGTERM or SIGINT, stop accepting new connections, finish ongoing requests, and close resources like database connections before exiting.
I run npm audit regularly to check for known vulnerabilities and update affected packages. For critical projects, I use additional tools like Snyk or npm's audit CI integration.