Node.js
102 flashcards by MentisLibrary
The runtime and its event loop, ES modules and packaging, promises and cancellation, errors and events, files and streams, HTTP servers and clients, npm and semver, and child processes and worker threads.
- What is Node.js?
- A JavaScript runtime for building programs outside the browser. It pairs the V8 engine with libuv for asynchronous input and output, and adds a standard library for files, networking, processes and cryptography.
- What do V8 and libuv each do?
- V8 parses, compiles and executes the JavaScript. libuv provides the event loop, the thread pool, and the platform abstraction over asynchronous sockets, files, timers and child processes.
- Is Node single-threaded?
- Your JavaScript runs on one thread, but the process is not single-threaded: libuv keeps a thread pool for some operations, and you can add more threads with worker threads.
- What does the libuv thread pool handle?
- Operations that have no asynchronous system call available: filesystem work, dns.lookup, and some crypto and zlib functions. Its size defaults to four and is set by the UV_THREADPOOL_SIZE environment variable.
- Name the phases of the event loop
- Timers, pending callbacks, idle and prepare, poll, check, and close callbacks. The loop runs them in that order on every turn.
- process.nextTick vs queueMicrotask vs a promise callback
- All three run before the loop moves on. The nextTick queue drains first and completely, then the promise microtask queue, which queueMicrotask also uses.
- setTimeout(fn, 0) vs setImmediate(fn)
- setImmediate runs in the check phase, right after the poll phase. setTimeout with zero runs in the timers phase of a later turn.
- What does blocking the event loop mean?
- Running synchronous JavaScript long enough that no other callback can run. Every pending request, timer and socket waits behind it.
- What is in process.argv?
- The command line arguments as an array. Index 0 is the node executable path, index 1 is the script path, and the arguments you passed start at index 2.
- How should configuration reach a Node program?
- Through environment variables read from process.env, validated once at startup, so the same build runs in every environment.
- process.exit(1) vs process.exitCode = 1
- process.exit terminates immediately and can truncate pending writes to stdout or a file. Setting process.exitCode lets the process finish naturally with that status.
- How do you shut a Node server down gracefully?
- Listen for SIGTERM, stop accepting new connections with server.close(), let in-flight requests finish, close the database pool, and exit.
- What does node --watch do?
- Restarts the process when a file it loaded changes, which removes the need for a separate reloader in development.
- What is the built-in test runner?
- Node ships a test runner. Write tests with the node:test module and assertions from node:assert, then run node --test.
- ES modules vs CommonJS
- ES modules use import and export, are statically analysed and resolved asynchronously. CommonJS uses require and module.exports and loads synchronously.
- How do you turn on ES modules?
- Set "type": "module" in package.json, which makes every .js file in that package an ES module, or name individual files .mjs.
- Default vs named exports
- A module may have one default export and any number of named ones. Named exports are imported by exactly their name; the default is imported under whatever name you choose.
- What does dynamic import() return?
- A promise for the module namespace object, so a module can be loaded conditionally or lazily at runtime.
- What is top-level await?
- In an ES module you may use await at the top level of the file, outside any function.
- How do you get the current directory in an ES module?
- There is no __dirname. Derive it from import.meta.url with fileURLToPath, or build a URL relative to it.
- What is createRequire for?
- Creating a CommonJS require function inside an ES module, for the rare package or JSON file that can only be loaded that way.
- Why write node:fs instead of fs?
- The node: prefix says unambiguously that the specifier is a built-in module. It cannot be shadowed by a package of the same name in node_modules, and it makes the intent obvious to readers and tooling.
- What does the exports field in package.json do?
- Declares the module's public entry points. Anything not listed cannot be imported by consumers, so internal files stay internal.
- main vs exports
- main names a single fallback entry point for older tooling. exports defines the full public surface and takes precedence when both are present.
- Are file extensions required in ES module imports?
- Yes, for relative and absolute specifiers. import './util.js' works; import './util' does not.
- What happens with a circular import in ES modules?
- The modules still load, and bindings are live, but a binding read before its module finished evaluating throws a temporal dead zone error.
- Why is import hoisted?
- Import declarations are static: they are resolved and the modules are evaluated before any code in the importing module runs, wherever the statement appears in the file.
- What is an error-first callback?
- The historical Node convention: the callback's first parameter is an error or null, and the result follows.
- What does util.promisify do?
- Wraps a function that takes an error-first callback so it returns a promise instead.
- Why does try/catch not catch an error from a callback?
- Because the callback runs on a later turn of the event loop, long after the try block has finished and its stack has unwound.