Questions 21–40 of 200 · 0 of 20 on this page marked learned
21.nodejs-0021Hardsenior
How do you get __dirname and require in an ES module, and how do CommonJS and ESM interoperate?
In ESM use import.meta.dirname and import.meta.filename (Node 20.11 and later), or fileURLToPath(import.meta.url). Use createRequire when you need require. ESM can import CJS directly. CJS can use dynamic import(), and since Node 22.12 can also call require() on an ES module that has no top-level await.
Full answer
ESM has no __dirname, __filename or require. The replacements:
import.meta.url: the file URL of the current module.
import.meta.dirname and import.meta.filename: direct strings, added in Node 20.11 and 21.2.
fileURLToPath(import.meta.url) and path.dirname(...): the older, portable form.
createRequire(import.meta.url): returns a require function for loading CJS packages or reading JSON in the old way.
JSON in ESM: import data from './x.json' with { type: 'json' }. The import attribute is required.
Interop rules:
ESM importing CJS: works. The default import is module.exports. Named imports work only when Node can detect them statically, so the safe form is the default import and then destructuring.
CJS loading ESM: use await import('./x.mjs'). This returns a promise, so it only works in async code. From Node 22.12, require('./x.mjs') also works if that ESM graph has no top-level await. The result is the module namespace object.
Dual packages publish both formats through the exports field, with the "import" and "require" conditions. Watch out for the dual package hazard: two copies of the same package (one CJS, one ESM) with separate state.
A migration tip: move one package at a time, start with leaf modules, and convert to ESM only when all the callers can handle it.
javascript
// Save as app.mjs
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
console.log('dirname forms agree:', import.meta.dirname === path.dirname(fileURLToPath(import.meta.url)));
console.log('filename matches the URL:', import.meta.filename === fileURLToPath(import.meta.url));
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'interop-'));
fs.writeFileSync(path.join(dir, 'data.json'), JSON.stringify({ course: 'Node.js', hours: 12 }));
fs.writeFileSync(path.join(dir, 'util.mjs'), "export const twice = (n) => n * 2;\n");
fs.writeFileSync(path.join(dir, 'old.cjs'), "const { twice } = require('./util.mjs'); module.exports = twice(21);\n");
// 1. JSON import with the required attribute.
const data = await import(path.join(dir, 'data.json'), { with: { type: 'json' } });
console.log('json import:', data.default);
// 2. require() inside ESM through createRequire.
const require = createRequire(import.meta.url);
console.log('require of a json file:', require(path.join(dir, 'data.json')).hours);
// 3. A CommonJS file that uses require() on an ES module.
console.log('CJS requires ESM:', require(path.join(dir, 'old.cjs')));
fs.rmSync(dir, { recursive: true });
Part 3 needs Node 22.12 or later. On older versions use await import() inside the CommonJS file. Save it as app.mjs and run it with node app.mjs.
Output (Node.js v24.22.1, same on two runs):
dirname forms agree: true
filename matches the URL: true
json import: { course: 'Node.js', hours: 12 }
require of a json file: 12
CJS requires ESM: 42
Key points
Use import.meta.dirname or fileURLToPath for paths.
createRequire gives require inside ESM.
JSON import needs the attribute with { type: 'json' }.
require(esm) works from Node 22.12 if there is no top-level await.
Dual packages can load two copies of the same code.
Common mistakes
Using __dirname in an ES module and getting a ReferenceError.
Importing JSON without the type attribute.
Relying on named imports from a CJS package that Node cannot analyse.
Publishing a package with both formats without testing both.
Follow-ups
What is the dual package hazard?
How would you migrate a large CJS code base to ESM?
How do bundlers treat these two formats?
Tips
Give the Node version for each feature. Interviewers often ask.
Say 'default import, then destructure' for CJS packages.
Mention exports conditions when asked about libraries.
22.nodejs-0022Easyfresher
What is the difference between module.exports and exports in CommonJS?
exports is a variable that starts as a reference to module.exports. Adding properties to either works. Assigning a new value to exports only changes the local variable, and require returns module.exports, so the assignment is lost. To export a function or a class, assign it to module.exports.
Full answer
Inside every CommonJS file, Node wraps your code in a function and gives it exports, require, module, __filename and __dirname. At the start, exports and module.exports point to the same empty object.
require() always returns module.exports, never the exports variable.
That is why these two forms behave in different ways:
exports.add = ... and module.exports.add = ...: both add a property to the shared object. Both work.
module.exports = function () {}: replaces the exported object. This works.
exports = function () {}: only repoints the local variable. module.exports is still the old empty object. The importer gets {}.
Use exports.name = value for several named exports. Use module.exports = value when the module has a single main export, such as a class or a function. Do not mix both styles in one file, because assigning module.exports later throws away the properties you added to exports.
ES modules do not have this issue because export statements are syntax, not objects.
The 'lost' module exports an empty object because the assignment never reaches module.exports. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
exports.hello: function
module.exports = fn: function
exports = fn (lost): {}
mixed styles: {"b":2}
Key points
require returns module.exports.
exports and module.exports start as the same object.
Assigning to exports breaks the link.
Use module.exports for a single export, exports.x for many.
Common mistakes
Writing exports = something and wondering why require returns {}.
Mixing exports.x and module.exports = in one file.
Exporting a class with exports.MyClass = and then calling require() as a function.
Thinking the same rules apply to ES modules.
Follow-ups
Why does Node wrap modules in a function?
How does the same example look with ES modules?
How do circular dependencies interact with module.exports replacement?
Tips
Draw two arrows from the names to one object, then cut one of them.
State that require returns module.exports in one short sentence.
Run the snippet before an interview. It takes a minute and it sticks.
23.nodejs-0023Easyfresher
What are the most important fields in package.json?
package.json describes a project. The key fields are name, version, type, main or exports, scripts, dependencies, devDependencies, peerDependencies and engines. npm reads them to install packages, run commands, and decide which files a published package exposes.
Full answer
Important fields:
name and version: the identity of the package. A published name must be unique on the registry.
type: "module" or "commonjs". Decides how .js files are loaded.
main: the entry file for require(). exports: a modern map of entry points that also blocks access to other files.
scripts: named commands run with npm run <name>. start and test have shortcuts (npm start, npm test). npm also runs pre and post hooks, for example prebuild before build.
dependencies: packages needed at run time. They are installed in production.
devDependencies: packages needed only for development, such as test runners and linters.
peerDependencies: packages the host project must provide, like a plugin that expects react. They state a compatible range and are not installed by default for the library itself.
optionalDependencies: install may fail without breaking the install.
engines: the Node versions the project supports. npm warns, and with engine-strict it fails.
files and .npmignore: what is included when you publish.
private: true: blocks accidental publishing.
bin: maps command names to files, for command-line tools.
npm install adds to dependencies by default and --save-dev adds to devDependencies. In production, npm ci --omit=dev installs only what the app needs at run time.
The JSON is a sample. The snippet shows how tools read the fields. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
package: attendance-tracker@1.4.2 | module type: module
scripts you can run: start, test, prebuild, build
needed in production: [ 'express' ]
only for development: [ 'eslint' ]
host must provide: { react: '>=18' }
minimum Node version rule: >=20
Key points
scripts, dependencies and type are used every day.
dependencies are needed at run time. devDependencies are only for development.
peerDependencies tell the host project which versions to supply.
exports controls the public entry points of a package.
Common mistakes
Putting build tools in dependencies of an application.
Forgetting that private: true prevents publishing.
Using main and exports together and not testing both.
Believing engines blocks installs by default. It only warns unless engine-strict is set.
Follow-ups
What is the difference between npm run and npx?
What do pre and post scripts do?
How do you publish only the dist folder?
Tips
Group the fields by purpose. Do not list them in random order.
Explain peerDependencies with a plugin example.
Mention exports, as it is the modern entry point.
24.nodejs-0024Easyfresher
How does semantic versioning work, and what do ^ and ~ mean in package.json?
Semver uses MAJOR.MINOR.PATCH. A patch fixes bugs, a minor adds features without breaking, and a major may break things. ^1.2.3 allows changes that keep the left-most non-zero digit (>=1.2.3 <2.0.0). ~1.2.3 allows only patch updates (>=1.2.3 <1.3.0).
Full answer
A version has three numbers: MAJOR.MINOR.PATCH, for example 4.18.2.
Increase PATCH for a backward compatible bug fix.
Increase MINOR for a backward compatible new feature.
Increase MAJOR for a change that can break users.
Range operators in package.json:
1.2.3: exactly this version.
~1.2.3: patch updates only. Same as >=1.2.3 <1.3.0.
^1.2.3: minor and patch updates. Same as >=1.2.3 <2.0.0. This is the default npm writes.
>=1.2.3, <2.0.0, 1.x and *: comparison and wildcard ranges.
Versions below 1.0.0 are treated as unstable, so the caret is stricter: ^0.2.3 means >=0.2.3 <0.3.0, and ^0.0.3 means exactly 0.0.3.
A pre-release such as 2.0.0-beta.1 is lower than 2.0.0 and is not matched by a normal range unless the range itself names a pre-release on the same version.
Semver depends on authors following the rules. A minor release can still break you, which is why a lock file and automated tests matter. In real projects use the semver package (the one npm itself uses) instead of writing your own parser.
javascript
// A tiny teaching version of the rules. Use the 'semver' package in real code.
const parse = (v) => v.split('.').map(Number);
const compare = (a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
function limits(range) {
const mark = range[0];
const [major, minor, patch] = parse(/[\^~]/.test(mark) ? range.slice(1) : range);
const low = [major, minor, patch];
if (mark === '~') return [low, [major, minor + 1, 0]];
if (mark === '^') {
if (major > 0) return [low, [major + 1, 0, 0]];
if (minor > 0) return [low, [0, minor + 1, 0]];
return [low, [0, 0, patch + 1]];
}
return [low, [major, minor, patch + 1]]; // exact version
}
function satisfies(version, range) {
const [low, high] = limits(range);
const v = parse(version);
return compare(v, low) >= 0 && compare(v, high) < 0;
}
const checks = [
['1.9.0', '^1.2.3'], ['2.0.0', '^1.2.3'], ['1.2.9', '~1.2.3'], ['1.3.0', '~1.2.3'],
['0.2.9', '^0.2.3'], ['0.3.0', '^0.2.3'], ['0.0.4', '^0.0.3'], ['1.2.3', '1.2.3'],
];
for (const [version, range] of checks) {
console.log(version.padEnd(6), 'matches', range.padEnd(7), '->', satisfies(version, range));
}
The helper handles only plain x.y.z versions and the three range styles above. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
1.9.0 matches ^1.2.3 -> true
2.0.0 matches ^1.2.3 -> false
1.2.9 matches ~1.2.3 -> true
1.3.0 matches ~1.2.3 -> false
0.2.9 matches ^0.2.3 -> true
0.3.0 matches ^0.2.3 -> false
0.0.4 matches ^0.0.3 -> false
1.2.3 matches 1.2.3 -> true
Key points
MAJOR.MINOR.PATCH with breaking, feature and fix meanings.
^ allows minor and patch updates. ~ allows patch updates.
0.x versions follow stricter caret rules.
A lock file protects against surprise updates.
Common mistakes
Thinking ^ never lets a breaking change in.
Treating ^0.2.3 like ^1.2.3.
Not committing the lock file, so versions drift between machines.
Using * or latest for production dependencies.
Follow-ups
What is a pre-release version and how is it ordered?
What does npm update do with a caret range?
How would you pin a transitive dependency?
Tips
Say 'left-most non-zero digit' for the caret rule.
Mention 0.x as the usual trap.
Add that a lock file, not the range, makes installs repeatable.
25.nodejs-0025Mediummid
What does package-lock.json do, and what is the difference between npm install and npm ci?
package-lock.json records the exact version, download location and integrity hash of every package in the dependency tree. npm install can update it, while npm ci installs exactly what the lock file says, deletes node_modules first, and fails if package.json and the lock file disagree. Use npm ci in CI and builds.
Full answer
package.json holds ranges (^4.17.0). Without more information, two installs on different days can pick different versions. package-lock.json fixes that. It lists the whole tree, direct and transitive, with:
the exact resolved version,
the resolved URL of the tarball,
an integrity hash (a SHA-512 checksum) that npm verifies after download,
the dependency edges, and flags such as dev or optional.
Commit the lock file for applications. For libraries it is also committed, but consumers ignore it, because they get their own lock file.
npm install reads package.json and the lock file, adds missing packages, may update the lock file when ranges allow, and changes node_modules in place. npm ci (clean install):
requires an existing lock file,
removes node_modules first,
installs exactly the locked tree, and never writes to package.json or the lock file,
exits with an error when package.json and the lock file do not match,
is usually faster in CI, and gives repeatable builds.
The integrity hash is also a security check: if the tarball content changes for the same version, installation fails. Review lock file changes in pull requests, since a changed resolved URL or integrity value is worth a question.
javascript
// A small sample of a lock file (lockfileVersion 3). Real files are much longer.
const lock = JSON.parse(`{
"name": "attendance-tracker",
"lockfileVersion": 3,
"packages": {
"": { "name": "attendance-tracker", "dependencies": { "express": "^4.19.2" } },
"node_modules/express": {
"version": "4.19.2",
"resolved": "https://registry.npmjs.org/express/-/express-4.19.2.tgz",
"integrity": "sha512-sample-hash-1",
"dependencies": { "accepts": "~1.3.8" }
},
"node_modules/accepts": {
"version": "1.3.8",
"resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
"integrity": "sha512-sample-hash-2"
}
}
}`);
const root = lock.packages[''];
console.log('range in package.json:', 'express', root.dependencies.express);
for (const [location, info] of Object.entries(lock.packages)) {
if (!location) continue;
console.log(
location.replace('node_modules/', '').padEnd(8),
'locked at', info.version.padEnd(7),
'| has integrity hash:', Boolean(info.integrity),
);
}
console.log('transitive dependency pulled in by express:', Object.keys(lock.packages['node_modules/express'].dependencies));
The lock file text is a made-up sample with fake hashes. The code shows how its structure maps ranges to exact versions. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
range in package.json: express ^4.19.2
express locked at 4.19.2 | has integrity hash: true
accepts locked at 1.3.8 | has integrity hash: true
transitive dependency pulled in by express: [ 'accepts' ]
Key points
The lock file stores exact versions and integrity hashes for the full tree.
npm ci installs exactly the lock file and fails on a mismatch.
npm install may update the lock file.
Use npm ci in CI and Docker builds.
Common mistakes
Adding package-lock.json to .gitignore in an application.
Running npm install in CI and getting different versions than on the laptop.
Editing the lock file by hand.
Mixing npm, yarn and pnpm lock files in one project.
Follow-ups
How do you update one dependency safely?
What does npm audit read?
How do overrides in package.json change the lock file?
Tips
Contrast the two commands in a table-like sentence: 'install resolves, ci replays'.
Mention integrity hashes as a security feature.
Say that CI and Docker builds should use npm ci.
26.nodejs-0026Hardsenior
How does Node.js find a package for require('name') or import 'name', and what does the exports field change?
For a bare name, Node looks in node_modules next to the importing file, then in each parent directory. Inside the package, the exports field (when present) lists the only allowed entry points and can pick different files for import and require. Paths not listed are blocked with ERR_PACKAGE_PATH_NOT_EXPORTED.
Full answer
For require('left-pad') or import 'left-pad', Node does not search your whole disk. It follows a fixed walk:
Core modules first ('node:fs', and also 'fs').
Relative or absolute paths ('./x', '/x') are loaded as files, or as directories with an index file or package.json main.
Bare names are searched in node_modules next to the importing file, then in the parent directory's node_modules, up to the root. The first match wins. The list of folders is visible with require.resolve.paths('name').
Inside the found package, Node reads package.json:
Without exports, main decides the entry (default index.js), and any file inside the package can be required by path (require('pkg/lib/internal.js')).
With exports, only the listed paths are public. Anything else throws ERR_PACKAGE_PATH_NOT_EXPORTED. This lets a library hide its internal files and change them without a breaking release.
Conditions choose a file by how the package is loaded: "import" for ESM, "require" for CJS, "node", "default", and custom ones used by tools. The order matters, and "default" should be last.
Package managers shape this tree. npm hoists packages to reduce copies. pnpm uses links so a package can only reach its declared dependencies. Both rely on the same lookup rules.
The package is built in a temporary folder, so the snippet needs no install step. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
require("greeter"): loaded the CommonJS build
require("greeter/feature"): public feature
require("greeter/lib/secret.js") failed with: ERR_PACKAGE_PATH_NOT_EXPORTED
first lookup folder is inside the project: true
import "greeter": loaded the ESM build
Key points
Bare names are looked up in node_modules, walking up the directory tree.
exports defines the public entry points and blocks the rest.
Conditions such as import and require select different files.
require.resolve and require.resolve.paths show what Node will use.
Common mistakes
Reaching into package internals with deep imports and breaking when the author adds exports.
Putting default before the other conditions in the exports map.
Forgetting that main is ignored when exports is present in modern Node.
Assuming the first match in node_modules is always the newest version.
Follow-ups
What is the difference between require.resolve and require?
How does pnpm change the lookup?
Why can two copies of the same package appear in one project?
Tips
Say the search order out loud: core, relative, node_modules up the tree.
Explain exports as an encapsulation tool, not only a convenience.
Know the error code ERR_PACKAGE_PATH_NOT_EXPORTED.
27.nodejs-0027Easyfresher
What are error-first callbacks, and why does try/catch not catch errors from asynchronous callbacks?
An error-first callback receives (err, result), and err is null on success. try/catch only catches errors thrown while its block is running on the call stack. An async callback runs later on a new stack, after the try block has ended, so the error must be passed through the callback, a promise or an event.
Full answer
Node's older APIs follow one convention: the callback is the last argument, and its first parameter is an error. If the operation worked, err is null or undefined, and the result follows. The first line of every callback should be the error check, and the function should return after handling it.
try/catch works with the call stack. When the engine runs the try block, any exception thrown during that block, directly or through functions it calls, is caught. fs.readFile(path, cb) only starts the work and returns. The try block ends. Later, the event loop calls cb on a new, empty stack. An exception thrown there has no surrounding try, so it becomes an uncaught exception and ends the process.
That is why Node APIs report operational errors (missing file, closed socket) through the callback, a rejected promise, or an 'error' event, and keep throw for programmer mistakes such as wrong argument types.
How to move to promises: util.promisify(fs.readFile) wraps a callback function that follows the convention, and the fs/promises module already returns promises. With await, try/catch works again, because await resumes the function on a stack where the try block is still active.
javascript
const fs = require('node:fs');
const { promisify } = require('node:util');
// 1. try/catch does not see the failure, the callback does.
try {
fs.readFile('/no/such/file.txt', (err, data) => {
if (err) {
console.log('3. callback received the error:', err.code);
return; // stop here, do not use data
}
console.log(data.length);
});
console.log('1. try block finished normally');
} catch (err) {
console.log('never printed:', err.code);
}
console.log('2. code after try/catch');
// 2. With promises and await, try/catch works again.
const readFile = promisify(fs.readFile);
(async () => {
try {
await readFile('/no/such/file.txt');
} catch (err) {
console.log('4. await + try/catch caught:', err.code);
}
})();
The numbers show the order: the try block ends long before the callback runs. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
1. try block finished normally
2. code after try/catch
3. callback received the error: ENOENT
4. await + try/catch caught: ENOENT
Key points
Error-first: callback(err, result), check err first and return.
try/catch covers only synchronous code on the current stack.
Operational errors travel by callback, rejection or 'error' event.
promisify or fs/promises with await gives back try/catch.
Common mistakes
Wrapping an asynchronous call in try/catch and expecting it to catch the callback error.
Calling the callback twice, once with an error and once with a result.
Forgetting return after handling err, so the code continues with undefined data.
Throwing inside a callback instead of passing the error on.
Follow-ups
What does util.promisify need from a function to work?
How do events report errors?
What is the difference between an operational error and a programmer error?
Tips
Draw two stacks to explain why the catch is skipped.
Say 'return after handling the error' when you mention callbacks.
Mention promisify as the bridge to modern code.
28.nodejs-0028Easyfresher
How do you handle errors with async/await, and how do Promise.all, Promise.allSettled and 'return await' differ?
A rejected promise inside an awaited expression throws, so try/catch catches it. Promise.all rejects as soon as any promise rejects and ignores the others' results. Promise.allSettled waits for all and reports each outcome. In a try block, 'return somePromise' skips the catch, while 'return await somePromise' keeps it.
Full answer
Inside an async function, await turns a rejected promise into a thrown exception at that line. Wrap the awaited call in try/catch, or let the error propagate: an async function returns a promise that rejects with the error, and the caller handles it.
Running several tasks:
Promise.all([...]): resolves with all results in order. If any promise rejects, the result rejects with that first error. The other promises keep running, but their results and later errors are ignored.
Promise.allSettled([...]): never rejects. It resolves with an array of { status: 'fulfilled', value } or { status: 'rejected', reason }. Use it for batch jobs where each item may fail by itself, such as sending 100 emails.
Promise.race: settles with the first outcome. Promise.any: resolves with the first success and rejects with an AggregateError only if all fail.
A trap with return: inside try, return promise does not wait. The function leaves the try block at once, and a later rejection goes to the caller, not to your catch. Write return await promise when you want the local catch to run (or when a finally block must run after completion).
Another trap: an async function with a missing await. The promise is not handled, and a rejection becomes an unhandledRejection event, which ends the process in current Node.
Without await, the rejection skips the local catch and reaches the caller. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
Promise.all rejected with: physics failed
[ 'ok: maths', 'failed: physics failed', 'ok: chemistry' ]
return promise -> caller caught: without await: inner failure
return await promise -> caught inside
Key points
await converts rejections into exceptions that try/catch can catch.
Promise.all fails fast. Promise.allSettled reports every outcome.
return await keeps the local catch active.
A forgotten await creates an unhandled rejection.
Common mistakes
Using await in a loop for independent tasks and making them run one after another.
Using Promise.all for a batch where one failure must not hide the others.
Writing try { return promise } catch and expecting the catch to run.
Putting an async function in forEach and expecting it to be awaited.
Follow-ups
How would you run 1,000 tasks with at most 10 at a time?
What does Promise.any return when all promises fail?
What happens to the promises that are still running after Promise.all rejects?
Tips
Mention fail fast vs collect all in one sentence.
Use the return await trap to show depth.
Say that for independent work you start all promises first, then await them.
29.nodejs-0029Mediummid
What happens on an unhandled promise rejection or an uncaught exception in Node.js, and how should you handle them?
Since Node 15 an unhandled rejection throws and ends the process with exit code 1, unless an 'unhandledRejection' handler exists. An uncaught exception also ends the process unless an 'uncaughtException' handler exists. Handlers should log, flush, and exit, because the process may be in an unknown state.
Full answer
An unhandled rejection is a promise that rejects when nothing has attached a .catch or try/await around it. By default, Node 15 and later treat it like an uncaught exception: it prints the error and exits with code 1. Older versions only printed a warning.
An uncaught exception is a thrown error that no try/catch caught. The default is to print the stack and exit with code 1.
Use them as a last line of defence for logging and clean-up, not for carrying on. After an unexpected error, application state may be half updated: a lock not released, a transaction open, a socket half written. The safe sequence is: log the error with context, stop accepting new work, finish or abandon current work with a timeout, and exit with a non-zero code. A process manager (systemd, Docker, Kubernetes, pm2) then starts a fresh process.
Prevent the problem at the source: await or return every promise, add .catch to fire-and-forget calls, and use ESLint rules such as no-floating-promises.
Also remember that process.on('exit') callbacks can only run synchronous code, so flush logs before that point.
javascript
const { spawnSync } = require('node:child_process');
function runChild(label, code) {
const r = spawnSync(process.execPath, ['-e', code], { encoding: 'utf8' });
console.log(label);
console.log(' exit code:', r.status);
console.log(' stdout: ', r.stdout.trim() || '(empty)');
console.log(' stderr mentions the error:', r.stderr.includes('marks service down'));
}
runChild('1. unhandled rejection, no handler',
"Promise.reject(new Error('marks service down'));");
runChild('2. unhandled rejection with a handler that logs and exits',
`process.on('unhandledRejection', (reason) => {
console.log('logged:', reason.message);
process.exit(1);
});
Promise.reject(new Error('marks service down'));`);
runChild('3. uncaught exception with a handler that logs and exits',
`process.on('uncaughtException', (err, origin) => {
console.log('logged:', err.message, '| origin:', origin);
process.exitCode = 1;
process.exit();
});
setTimeout(() => { throw new Error('marks service down'); }, 0);`);
Each case runs in a child process, so the parent keeps running. Cases 1 and 2 are errors on purpose, shown through exit codes. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
1. unhandled rejection, no handler
exit code: 1
stdout: (empty)
stderr mentions the error: true
2. unhandled rejection with a handler that logs and exits
exit code: 1
stdout: logged: marks service down
stderr mentions the error: false
3. uncaught exception with a handler that logs and exits
exit code: 1
stdout: logged: marks service down | origin: uncaughtException
stderr mentions the error: false
Key points
Node 15 and later exit with code 1 on an unhandled rejection by default.
Handlers are for logging and graceful exit, not for continuing.
Let a supervisor restart the process.
Prevent them with await, return and lint rules.
Common mistakes
Using an uncaughtException handler to keep the server running as if nothing happened.
Calling process.exit() immediately and cutting off pending log writes.
Throwing inside a promise chain without a final catch.
Assuming async functions called without await are safe.
Follow-ups
How would you shut down gracefully after an uncaught exception?
What does the --unhandled-rejections flag change?
Why can finally blocks not run after process.exit()?
Tips
Name the exit code (1) and the Node version (15) that changed the default.
Say 'log, stop accepting work, exit, let the supervisor restart'.
Mention lint rules for floating promises.
30.nodejs-0030Hardsenior
How do you design custom errors in Node.js, and what is the difference between operational errors and programmer errors?
Create error classes that extend Error, with a stable code, an HTTP status when needed, and the original error in the cause option. Operational errors are expected runtime problems (bad input, a down service) that code can handle. Programmer errors are bugs (TypeError, wrong arguments) that should crash and be fixed.
Full answer
Why custom errors: callers should branch on a stable property, not on message text. A good design has:
A base class AppError extends Error with name, code (a string like 'ORDER_NOT_FOUND'), and optionally statusCode and details.
Subclasses for common cases: ValidationError (400), NotFoundError (404), DependencyError (502).
The original error kept as the cause: new AppError('Could not load marks', { cause: err }). Node prints the cause chain, and err.cause lets you log the root problem without losing context.
Error.captureStackTrace(this, this.constructor) is optional in modern V8, since the stack is captured in the Error constructor already.
Operational vs programmer errors:
Operational: the program is right but the world is not. Examples: user sent invalid JSON, a database timed out, a file is missing. Handle them: retry, show a clear message, return 4xx or 5xx.
Programmer: a bug. Examples: reading a property of undefined, passing a number where a string is required. Do not catch them to hide them. Log, crash, restart, fix.
For many errors at once (validation of a form with five invalid fields, or Promise.any failing), use AggregateError, which holds an errors array.
Never send stack traces or internal messages to clients. Map the error to a safe message and code in one place, such as an HTTP error middleware, and log the full detail on the server.
javascript
class AppError extends Error {
constructor(message, { code = 'APP_ERROR', statusCode = 500, cause } = {}) {
super(message, { cause });
this.name = this.constructor.name;
this.code = code;
this.statusCode = statusCode;
}
}
class NotFoundError extends AppError {
constructor(what, options) {
super(`${what} not found`, { code: 'NOT_FOUND', statusCode: 404, ...options });
}
}
function findStudent(id) {
try {
if (id !== 1) throw new RangeError('row missing in the in-memory table'); // low-level detail
return { id, name: 'Asha' };
} catch (err) {
throw new NotFoundError(`Student ${id}`, { cause: err });
}
}
// Convert errors to safe responses in one place.
function toResponse(err) {
if (err instanceof AppError) return { status: err.statusCode, body: { code: err.code, message: err.message } };
return { status: 500, body: { code: 'INTERNAL', message: 'Something went wrong' } }; // programmer error: no details
}
try {
findStudent(7);
} catch (err) {
console.log('name:', err.name, '| code:', err.code, '| instanceof AppError:', err instanceof AppError);
console.log('cause:', err.cause.name + ': ' + err.cause.message);
console.log('response:', JSON.stringify(toResponse(err)));
console.log('unknown error response:', JSON.stringify(toResponse(new TypeError('x is undefined'))));
}
const many = new AggregateError([new Error('name is empty'), new Error('age must be a number')], 'Validation failed');
console.log(many.message, '->', many.errors.map((e) => e.message));
The unknown TypeError shows the safe fallback: the client gets no internal detail. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
name: NotFoundError | code: NOT_FOUND | instanceof AppError: true
cause: RangeError: row missing in the in-memory table
response: {"status":404,"body":{"code":"NOT_FOUND","message":"Student 7 not found"}}
unknown error response: {"status":500,"body":{"code":"INTERNAL","message":"Something went wrong"}}
Validation failed -> [ 'name is empty', 'age must be a number' ]
Key points
Extend Error, add a stable code, and keep the original error in cause.
Branch on code or instanceof, never on message text.
Operational errors are handled. Programmer errors crash and get fixed.
AggregateError groups several errors.
Map errors to safe client responses in one place.
Common mistakes
Matching errors by message text.
Returning err.message or err.stack of an unknown error to the client.
Catching a TypeError and carrying on, which hides a bug.
Losing the original error when wrapping, so the root cause is gone from the logs.
Follow-ups
How would you log a cause chain in JSON?
Should a library throw strings? Why not?
How do you test that a function throws a specific error class?
Tips
Define both error kinds in one sentence each, with an example.
Show the cause option, since many candidates still use it rarely.
Say where the mapping to HTTP responses lives.
31.nodejs-0031Easyfresher
How does EventEmitter work in Node.js, and what is special about the 'error' event?
EventEmitter lets objects emit named events and lets other code listen with on, once and off. Listeners run synchronously in the order they were added when emit is called. If 'error' is emitted and no listener exists, Node throws the error, which can crash the process.
Full answer
Many core classes (streams, servers, sockets, processes) extend EventEmitter. It is Node's version of the observer pattern.
Main methods:
emitter.on(name, listener) or addListener: add a listener.
emitter.once(name, listener): the listener runs at most once.
emitter.off(name, listener) or removeListener: remove it.
emitter.emit(name, ...args): call every listener with the arguments. Returns true if there was at least one listener.
emitter.listenerCount(name) and eventNames().
Key behaviours:
emit is synchronous. All listeners finish before emit returns, in the order of registration. A slow listener blocks the emitter, and a listener that throws stops the remaining listeners and the exception goes to the caller of emit.
Listeners are called with this set to the emitter (not for arrow functions).
The event name 'error' is special. If emit('error', err) is called and no 'error' listener exists, the error is thrown. Always add an error listener to emitters that can fail, such as streams and sockets.
Emitting before anyone listens means the event is lost. Add listeners first.
To build your own, extend the class: class Order extends EventEmitter. Remember to call super() in the constructor.
javascript
const { EventEmitter } = require('node:events');
class Attendance extends EventEmitter {
mark(student, present) {
this.emit('marked', student, present);
if (!present) this.emit('absent', student);
}
}
const register = new Attendance();
register.on('marked', (student, present) => console.log('1. marked', student, present));
register.on('marked', (student) => console.log('2. second listener for', student));
register.once('absent', (student) => console.log('3. absence alert (once) for', student));
register.mark('Asha', true);
register.mark('Ravi', false);
register.mark('Meera', false); // the once listener is gone, no alert
console.log('absent listeners left:', register.listenerCount('absent'));
// emit is synchronous
register.on('ping', () => console.log('listener ran'));
register.emit('ping');
console.log('emit returned after the listener finished');
// 'error' without a listener throws
try {
register.emit('error', new Error('database offline'));
} catch (err) {
console.log('thrown because nobody listened:', err.message);
}
The alert for Meera does not print, because the once listener removed itself after the first absence. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
1. marked Asha true
2. second listener for Asha
1. marked Ravi false
2. second listener for Ravi
3. absence alert (once) for Ravi
1. marked Meera false
2. second listener for Meera
absent listeners left: 0
listener ran
emit returned after the listener finished
thrown because nobody listened: database offline
Key points
on, once, off and emit are the core API.
emit calls listeners synchronously in registration order.
An 'error' event without a listener throws.
Events emitted before listeners are attached are lost.
Common mistakes
Assuming emit is asynchronous.
Forgetting an 'error' listener and crashing the process.
Adding a listener after the event was already emitted.
Using an arrow function and expecting this to be the emitter.
Follow-ups
How would you make listeners run asynchronously?
What does emitter.prependListener do?
How does EventEmitter relate to streams?
Tips
Say 'synchronous' and 'error is special' without being asked.
Give a realistic example such as an order or attendance system.
Mention that streams, HTTP servers and sockets are emitters.
32.nodejs-0032Mediummid
What does the MaxListenersExceededWarning mean, and how do you find and fix an EventEmitter listener leak?
Node warns when more than 10 listeners are added for one event on one emitter, because that is usually a leak: code adds a listener on every request or call and never removes it. Fix the cause by adding once or removing listeners when done. Raise the limit only if many listeners are intended.
Full answer
Every listener keeps its function, and everything the function captures, alive for as long as the emitter lives. If a long-lived emitter (a database connection, process, a shared event bus) receives a new listener on every request, memory grows without end and every emit calls more and more functions.
Node helps by printing MaxListenersExceededWarning when more than defaultMaxListeners (10) listeners are added to one event name. The message shows the event name and the count. The warning is a hint, not the limit: the extra listeners are still added.
How to find the leak: read the event name in the warning, then search for the on() call. Run with node --trace-warnings to see where the listener was added. Check emitter.listenerCount(name) over time.
How to fix:
Use once when the listener should run a single time.
Pair each on with an off in clean-up code (a finally block, a close handler, a component unmount).
Add listeners once at start-up, not inside a request handler.
Use AbortSignal with events.once or events.on so waiting can be cancelled.
If the count is deliberately large (a server with many subscribers), raise it with emitter.setMaxListeners(n), or 0 for unlimited, after being sure it is intended.
javascript
const { EventEmitter } = require('node:events');
process.on('warning', (w) => console.log('warning event:', w.name, '| emitter event:', w.type, '| count:', w.count));
const bus = new EventEmitter();
// Leaky pattern: a new listener on every request, never removed.
function handleRequestLeaky() {
bus.on('config-changed', () => {});
}
for (let i = 0; i < 11; i++) handleRequestLeaky();
console.log('listeners after 11 leaky requests:', bus.listenerCount('config-changed'));
// Fixed pattern: remove the listener when the request is finished.
const fixedBus = new EventEmitter();
function handleRequestFixed() {
const onChange = () => {};
fixedBus.on('config-changed', onChange);
// ... request work ...
fixedBus.off('config-changed', onChange); // clean-up
}
for (let i = 0; i < 11; i++) handleRequestFixed();
console.log('listeners after 11 fixed requests:', fixedBus.listenerCount('config-changed'));
Node also prints the warning text to stderr, so you will see it in the terminal as well as in the 'warning' event output. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
listeners after 11 leaky requests: 11
listeners after 11 fixed requests: 0
warning event: MaxListenersExceededWarning | emitter event: config-changed | count: 11
Key points
More than 10 listeners per event triggers a warning.
The warning signals a probable leak, not a hard limit.
Fix with once, off, one-time registration or AbortSignal.
setMaxListeners is for intentional large counts.
Common mistakes
Silencing the warning with setMaxListeners(0) without finding the cause.
Adding listeners inside request handlers on a shared emitter.
Using an anonymous function and then being unable to remove it.
Ignoring the warning because the app still works.
Follow-ups
How would you debug a leak when no warning is shown?
What does node --trace-warnings print?
How can closures in listeners keep large objects alive?
Tips
Explain the leak with one picture: a growing list of functions inside a long-lived object.
Name the three fixes: once, off, register once.
Mention --trace-warnings as the debugging tool.
33.nodejs-0033Hardsenior
What advanced EventEmitter features should a senior developer know: events.once, events.on, prependListener and AbortSignal?
events.once(emitter, name) returns a promise for the next event and rejects if 'error' fires first. events.on(emitter, name) is an async iterator over events and can be cancelled with an AbortSignal. prependListener adds a listener before the existing ones. These let event code use async/await cleanly.
Full answer
Classic listeners work well for continuous events, but they are awkward when you want "wait for the next event and then continue". The events module has helpers for that:
events.once(emitter, 'ready') returns a promise that resolves with an array of the event arguments. If the emitter emits 'error' first, the promise rejects with it, and the listeners are removed in both cases. Pass { signal } to cancel the wait.
events.on(emitter, 'tick') returns an async iterator. Use for await to process events one by one. Events that arrive while your loop body is busy are queued. Break out of the loop or abort the signal to stop, which removes the listeners.
emitter.prependListener(name, fn) and prependOnceListener put a listener at the front of the list. Useful for a validation or logging step that must run first.
events.errorMonitor: a symbol you can listen to for errors without changing the normal rule that an unhandled 'error' still throws. Good for metrics.
new EventEmitter({ captureRejections: true }): if an async listener rejects, the rejection is sent to the 'error' event instead of becoming an unhandled rejection.
events.getEventListeners and events.setMaxListeners work with EventTarget too, since the browser style EventTarget also exists in Node.
A caution: emit is still synchronous. An async listener returns a promise that emit ignores, so errors inside it are not seen unless captureRejections is on.
javascript
const { EventEmitter, once, on } = require('node:events');
async function main() {
const feed = new EventEmitter();
// prependListener changes the order.
feed.on('result', () => console.log('listener 2 (added with on)'));
feed.prependListener('result', () => console.log('listener 1 (prepended)'));
feed.emit('result');
// once: wait for the next event with await.
setTimeout(() => feed.emit('ready', 'exam hall open', 42), 5);
const [message, seats] = await once(feed, 'ready');
console.log('once resolved with:', message, seats);
// once rejects when 'error' is emitted first.
setTimeout(() => feed.emit('error', new Error('hall closed')), 5);
try {
await once(feed, 'ready');
} catch (err) {
console.log('once rejected with:', err.message);
}
// on: async iteration with cancellation.
const controller = new AbortController();
setTimeout(() => {
feed.emit('mark', 'Asha', 78);
feed.emit('mark', 'Ravi', 91);
setTimeout(() => controller.abort(), 5);
}, 5);
try {
for await (const [name, marks] of on(feed, 'mark', { signal: controller.signal })) {
console.log('on received:', name, marks);
}
} catch (err) {
console.log('loop ended by:', err.name);
}
console.log('listeners left on "mark":', feed.listenerCount('mark'));
}
main();
The aborted loop ends with AbortError and removes its own listeners. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
listener 1 (prepended)
listener 2 (added with on)
once resolved with: exam hall open 42
once rejected with: hall closed
on received: Asha 78
on received: Ravi 91
loop ended by: AbortError
listeners left on "mark": 0
Key points
events.once is a promise for the next event, and rejects on 'error'.
events.on is an async iterator, cancelled with AbortSignal.
prependListener controls the order.
captureRejections routes async listener errors to 'error'.
Common mistakes
Using async listeners and expecting emit to wait for them.
Awaiting events.once after the event has already fired, so it waits forever.
Not passing a signal or timeout, so a wait can hang.
Forgetting that the result of events.once is an array.
Follow-ups
How do you add a timeout to events.once?
How does EventTarget differ from EventEmitter?
What does errorMonitor give you that an 'error' listener does not?
Tips
Start from the problem: 'wait for one event' is awkward with callbacks.
Mention cancellation, because it separates careful code from fragile code.
Know the one-line difference between sync emit and async listeners.
34.nodejs-0034Mediummid
What is the difference between child_process.spawn, exec, execFile and fork?
spawn starts a command and streams its output. exec runs a command in a shell and buffers all output in a callback. execFile runs a file directly without a shell, which is safer. fork starts a new Node process with a built-in message channel for communication.
Full answer
All four start another process. They differ in how output comes back and in how the command is run.
spawn(command, args): starts the process and gives you streams for stdin, stdout and stderr right away. No shell by default. Best for large or long-running output (video conversion, log tailing).
exec(commandString): runs the string in a shell (/bin/sh or cmd.exe). Collects stdout and stderr into strings and passes them to a callback when the process ends. There is a maxBuffer limit (1 MB by default), and a larger output makes it fail. Shell features such as pipes and wildcards work. Risk: building the string from user input allows command injection.
execFile(file, args): like exec but without a shell, and arguments are passed as an array, so there is no injection through the argument string. Output is buffered.
fork(modulePath, args): a special spawn for Node scripts. It adds an IPC channel: child.send(message) and process.on('message') work, and messages are structured data.
Choosing: streaming output uses spawn. A short command with small output and no shell features uses execFile. A shell pipeline written by you (not by users) uses exec. Splitting a Node program across processes uses fork, or worker_threads for lighter weight.
Handle the 'error' event (the command could not start) and the 'exit' or 'close' event (the exit code). A non-zero code is not an error event.
Each call runs a second Node process, so the example works on any system that has node. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
spawn output lines: [ 'line 1', 'line 2' ]
spawn exit code: 0
execFile result: 42
exec result: shell
fork reply: { doubled: 42 }
Key points
spawn streams, exec and execFile buffer.
exec uses a shell, execFile and spawn do not by default.
fork adds an IPC message channel for Node scripts.
Never build shell strings from user input.
Common mistakes
Using exec with a string that contains user input.
Running a command that prints a lot with exec and hitting maxBuffer.
Treating a non-zero exit code as an 'error' event.
Forgetting to kill child processes when the parent exits.
Follow-ups
How would you stop a child that runs too long?
What is the difference between 'exit' and 'close' events?
When is fork better than worker_threads?
Tips
Use a table in your head: stream or buffer, shell or no shell, IPC or not.
Say 'command injection' when exec comes up.
Add that fork processes are heavier than worker threads because each has its own V8.
35.nodejs-0035Mediummid
When and how do you use worker_threads in Node.js, and how is data passed between threads?
worker_threads runs JavaScript in a separate thread with its own event loop and V8 instance, so CPU-heavy work does not block the main thread. Threads talk with postMessage. Data is copied with the structured clone algorithm, transferred (ArrayBuffer moves without copying), or shared (SharedArrayBuffer).
Full answer
Use worker threads for CPU-bound work: image resizing, parsing a large file, hashing, compression in JavaScript, calculations. They do not help I/O-bound work, because async I/O already runs without blocking.
How it works:
new Worker(filename or code, { workerData }) starts a thread. Each worker has its own event loop, its own memory heap and its own module cache. Starting one costs tens of milliseconds and some megabytes, so reuse workers with a pool.
The worker file uses parentPort.postMessage(data) to send and parentPort.on('message') to receive. The main thread does the same with worker.postMessage and worker.on('message').
workerData is the initial copy of data given to the worker.
Passing data:
Copy (default): the structured clone algorithm copies objects, arrays, Maps, Dates, typed arrays. Functions and class instances with methods do not survive.
Transfer: put ArrayBuffers in a transfer list, postMessage(buf, [buf]). Ownership moves with no copy, and the sender's buffer becomes empty (byteLength 0).
Share: a SharedArrayBuffer is visible to both threads. Use Atomics to avoid races.
Errors: an uncaught exception in a worker emits 'error' on the Worker object, and 'exit' follows. Also available: worker.terminate(), and resourceLimits to cap memory.
javascript
const { Worker, isMainThread, parentPort, workerData } = require('node:worker_threads');
if (isMainThread) {
// ---- main thread ----
let ticks = 0;
const timer = setInterval(() => ticks++, 10); // proves the main thread stays free
const worker = new Worker(__filename, { workerData: { n: 36 } });
worker.once('message', (result) => {
clearInterval(timer);
console.log('fib(36) from the worker:', result);
console.log('main thread kept running while waiting:', ticks > 0);
// Transfer an ArrayBuffer: the main thread loses it.
const buffer = new ArrayBuffer(1024);
const second = new Worker(__filename, { workerData: { transfer: true } });
second.once('message', (size) => {
console.log('worker received', size, 'bytes | main copy length after transfer:', buffer.byteLength);
second.terminate();
});
second.postMessage(buffer, [buffer]);
});
worker.once('error', (err) => console.log('worker failed:', err.message));
} else if (workerData.transfer) {
// ---- worker that receives a transferred buffer ----
parentPort.once('message', (buffer) => parentPort.postMessage(buffer.byteLength));
} else {
// ---- worker that does CPU work ----
const fib = (n) => (n < 2 ? n : fib(n - 1) + fib(n - 2));
parentPort.postMessage(fib(workerData.n));
}
The same file acts as both the main program and the worker, which keeps the example short. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
fib(36) from the worker: 14930352
main thread kept running while waiting: true
worker received 1024 bytes | main copy length after transfer: 0
Key points
Use for CPU-bound work, not for I/O.
Each worker has its own event loop and heap.
Messages are cloned, transferred or shared.
Pool workers because start-up is costly.
Common mistakes
Using workers for network or file I/O.
Creating a new worker per request.
Sending huge objects by copy on every message.
Expecting functions or class instances to cross the thread boundary.
Follow-ups
How would you cancel a long worker task?
What is the difference between worker_threads and child_process.fork?
How do you share a counter safely between threads?
Tips
Say 'CPU-bound' first, then show the main thread stays responsive.
Describe the three ways to move data in one sentence each.
Bring up pooling before the interviewer asks.
36.nodejs-0036Hardsenior
How does the cluster module work, how does it share one port, and what are its limits?
cluster forks several Node processes (workers) from a primary process. The primary owns the listening socket and, on Linux and macOS, hands incoming connections to workers in round-robin order. It scales a server across CPU cores, but workers do not share memory, so in-process state and caches must move to an external store.
Full answer
A single Node process uses one core for JavaScript. The cluster module starts one worker process per core so a server can use them all.
How it works:
The primary process calls cluster.fork() several times. Each worker is a full Node process that runs the same script again, with cluster.isPrimary false.
When a worker calls server.listen(port), the request goes to the primary. The primary opens the socket once, accepts connections, and passes each one to a worker. The default policy is round-robin (except on Windows, where the operating system distributes connections).
Workers and the primary talk through IPC messages. cluster.on('exit') lets the primary replace a crashed worker.
Limits and trade-offs:
No shared memory. Sessions, rate-limit counters and caches kept in a variable differ per worker. Use Redis or a database.
Each worker has its own heap, so memory use is multiplied.
WebSocket and sticky sessions need extra care, because one client can land on different workers.
Round-robin does not balance by work. One worker can get all the slow requests.
Today most teams run one process per container and let Kubernetes or a load balancer scale instances. cluster, or a process manager such as pm2 in cluster mode, is still useful on a single machine.
worker_threads is the better tool for CPU work. cluster is for scaling request handling.
Always handle worker exit to keep capacity, and add graceful shutdown with worker.disconnect().
javascript
const cluster = require('node:cluster');
const http = require('node:http');
if (cluster.isPrimary) {
const WORKERS = 2;
const REQUESTS = 6;
let listening = 0;
const served = {};
for (let i = 0; i < WORKERS; i++) cluster.fork();
cluster.on('listening', (worker, address) => {
if (++listening < WORKERS) return;
// Both workers share one port. Send requests and see who answers.
let pending = REQUESTS;
const send = () => {
http.get({ port: address.port, host: '127.0.0.1', agent: false }, (res) => {
let body = '';
res.on('data', (c) => (body += c));
res.on('end', () => {
served[body] = (served[body] || 0) + 1;
if (--pending > 0) return send();
console.log('workers started:', WORKERS, '| requests sent:', REQUESTS);
console.log('answers per worker (round-robin):', Object.values(served));
console.log('different workers answered:', Object.keys(served).length);
cluster.disconnect();
});
});
};
send();
});
} else {
http.createServer((req, res) => res.end('worker ' + cluster.worker.id)).listen(0, '127.0.0.1');
}
Port 0 asks for any free port, and both workers share the one the primary opened. Requests are sent one at a time, so round-robin alternates between the workers. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
workers started: 2 | requests sent: 6
answers per worker (round-robin): [ 3, 3 ]
different workers answered: 2
Key points
One primary, many worker processes, one shared listening port.
Round-robin distribution (except on Windows).
No shared memory between workers.
Replace crashed workers from the primary.
Containers and orchestrators often replace cluster.
Common mistakes
Storing sessions or counters in process memory and running several workers.
Believing cluster uses threads.
Not restarting workers that crash.
Using cluster inside a container that is already scaled horizontally, then over-using memory.
Follow-ups
How would you do a zero-downtime restart with cluster?
How do you handle sticky sessions for WebSockets?
Why is cluster less common today than ten years ago?
Tips
Say who owns the socket (the primary) and how connections reach workers.
List the trade-offs. Interviewers expect the shared-state problem.
Compare with worker_threads in one sentence.
37.nodejs-0037Hardsenior
How can worker threads share memory safely with SharedArrayBuffer and Atomics?
A SharedArrayBuffer is a block of memory that several threads can read and write. Plain operations such as counter++ are not atomic, so updates can be lost. Atomics.add, compareExchange, wait and notify perform the operation as one indivisible step.
Full answer
Normally worker threads share nothing and copy messages. A SharedArrayBuffer (SAB) changes that. The same bytes appear in every thread that receives the buffer, and you view them through a typed array such as Int32Array.
The danger is the race condition. counter[0]++ is three steps: read, add, write. If two threads read the same old value, both write the same new value, and one increment disappears.
Atomics is the standard object for safe access:
Atomics.add, sub, and, or, xor: do the read-modify-write as one step, and return the old value.
Atomics.load and store: read and write with ordering guarantees.
Atomics.compareExchange(array, index, expected, new): the base of locks and lock-free algorithms.
Atomics.wait(array, index, value) and Atomics.notify(array, index, count): block a worker thread until another thread signals. Atomics.wait is not allowed on the main thread in browsers, and should not block the Node main thread either. Atomics.waitAsync is the non-blocking version.
A mutex built on compareExchange is possible, but prefer simpler designs: have one thread own the data and others send messages, or give each worker its own slice of the array and combine the results at the end.
Use SAB for large numeric data (images, matrices, counters, ring buffers). For ordinary objects, messages are simpler and safer.
javascript
const { Worker, isMainThread, workerData } = require('node:worker_threads');
const WORKERS = 4;
const ROUNDS = 100000;
if (isMainThread) {
const shared = new SharedArrayBuffer(8); // two 32-bit numbers
const counters = new Int32Array(shared); // [0] = atomic counter, [1] = plain counter
let finished = 0;
for (let i = 0; i < WORKERS; i++) {
const worker = new Worker(__filename, { workerData: shared });
worker.once('exit', () => {
if (++finished < WORKERS) return;
const expected = WORKERS * ROUNDS;
console.log('expected total:', expected);
console.log('Atomics.add total:', Atomics.load(counters, 0), '| correct:', Atomics.load(counters, 0) === expected);
console.log('plain ++ total never exceeds expected:', counters[1] <= expected);
});
}
} else {
const counters = new Int32Array(workerData);
for (let i = 0; i < ROUNDS; i++) {
Atomics.add(counters, 0, 1); // safe
counters[1]++; // unsafe: updates can be lost
}
}
The plain counter usually ends below the expected total, but the exact number changes between runs, so the snippet prints only the facts that are always true. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
expected total: 400000
Atomics.add total: 400000 | correct: true
plain ++ total never exceeds expected: true
Key points
SharedArrayBuffer is memory visible to all threads.
counter++ is not atomic and loses updates.
Atomics gives indivisible operations plus wait and notify.
Message passing is simpler when sharing is not needed.
Common mistakes
Using counter++ on shared memory from several threads.
Calling Atomics.wait on the main thread.
Sharing memory when messages would do.
Assuming a normal object or Map can live in a SharedArrayBuffer.
Follow-ups
How would you build a simple lock with compareExchange?
What is false sharing and why does it slow threads?
How is the data in a SAB laid out for strings or objects?
Tips
Start with the lost update picture: read, add, write.
Prefer message passing in your answer and treat SAB as the exception.
Mention wait and notify for the producer and consumer case.
38.nodejs-0038Hardsenior
How would you build a small worker pool for CPU-bound tasks?
Start a fixed number of workers (about the CPU count), keep a queue of tasks, and give each task to an idle worker. When a worker finishes, resolve that task's promise and take the next queued task. Handle worker errors by rejecting the task and replacing the worker, and terminate all workers on shutdown.
Full answer
Starting a worker for every task is slow and can use all the memory. A pool fixes both.
Design:
Size: os.availableParallelism() for CPU-bound work (or one less, to leave a core for the main thread).
Workers: created once, kept alive, waiting for messages.
Queue: tasks that arrive when all workers are busy wait in a FIFO array. For protection, limit its length and reject new tasks when it is full. That gives the caller backpressure instead of unbounded memory growth.
Dispatch: pool.run(data) returns a promise. If a worker is idle, send the task. If not, queue it. When a worker replies, resolve the matching promise, mark the worker idle, and start the next queued task.
Failure: if a worker emits 'error' or exits, reject its current task and start a replacement. Add a timeout per task and terminate a stuck worker.
Shutdown: stop accepting tasks, wait for running ones, then terminate all workers. Workers keep the process alive until they are terminated.
Matching replies to tasks is simple when each worker handles one task at a time. For several tasks per worker, add an id to each message.
Production libraries such as Piscina implement this with extras (task cancellation, resource limits, transferable support). In an interview, the structure above, with an explanation of the queue and failure handling, is the expected depth.
javascript
const { Worker, isMainThread, parentPort } = require('node:worker_threads');
if (isMainThread) {
class Pool {
constructor(size) {
this.queue = [];
this.idle = [];
this.all = [];
this.running = 0;
this.maxRunning = 0;
for (let i = 0; i < size; i++) {
const worker = new Worker(__filename);
this.all.push(worker);
this.idle.push(worker);
}
}
run(n) {
return new Promise((resolve, reject) => {
this.queue.push({ n, resolve, reject });
this.#dispatch();
});
}
#dispatch() {
while (this.idle.length > 0 && this.queue.length > 0) {
const worker = this.idle.pop();
const job = this.queue.shift();
this.running++;
this.maxRunning = Math.max(this.maxRunning, this.running);
const onMessage = (result) => {
worker.off('error', onError);
this.running--;
this.idle.push(worker);
job.resolve(result);
this.#dispatch();
};
const onError = (err) => {
worker.off('message', onMessage);
this.running--;
job.reject(err); // a real pool would also replace the dead worker here
};
worker.once('message', onMessage);
worker.once('error', onError);
worker.postMessage(job.n);
}
}
close() {
return Promise.all(this.all.map((w) => w.terminate()));
}
}
const pool = new Pool(2);
const sizes = [1000, 2000, 3000, 4000, 5000, 6000];
Promise.all(sizes.map((n) => pool.run(n))).then(async (results) => {
console.log('sum of 1..n for each task:', results);
console.log('tasks:', sizes.length, '| most tasks running at once:', pool.maxRunning);
await pool.close();
});
} else {
parentPort.on('message', (n) => {
let sum = 0;
for (let i = 1; i <= n; i++) sum += i;
parentPort.postMessage(sum);
});
}
Six tasks share two workers, so no more than two run at the same time. A production pool would also add a task timeout and replace crashed workers, as listed in the answer. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
sum of 1..n for each task: [ 500500, 2001000, 4501500, 8002000, 12502500, 18003000 ]
tasks: 6 | most tasks running at once: 2
Key points
Fixed number of long-lived workers plus a FIFO queue.
A task is a promise resolved by the worker's reply.
Handle errors, timeouts and replacement of dead workers.
Bound the queue to apply backpressure.
Terminate workers on shutdown, or the process will not exit.
Common mistakes
Creating a new worker for each request.
Leaving idle workers alive so the process never exits.
Letting the queue grow without a limit.
Ignoring worker crashes, which silently reduces capacity.
Follow-ups
How would you add per-task timeouts?
How would you prioritise urgent tasks?
When would you pick Piscina instead of your own pool?
Tips
Say the queue limit out loud. It shows you think about overload.
Describe failure handling before the interviewer asks.
Mention that workers must be terminated for a clean exit.
39.nodejs-0039Easyfresher
How do you create a basic HTTP server with Node's http module, and what do req and res give you?
http.createServer takes a handler that receives a request (a readable stream with method, url and headers) and a response (a writable stream). You set a status code and headers, then write the body and call end(). Frameworks such as Express are built on this same pair of objects.
Full answer
http.createServer((req, res) => { ... }) returns a server. The handler runs once for each request.
req (IncomingMessage) is a readable stream:
req.method ('GET', 'POST'), req.url (path and query string), req.headers (names in lower case).
The body arrives as chunks. For a GET request you can ignore it.
res (ServerResponse) is a writable stream:
res.statusCode = 404 or res.writeHead(200, headers) sets the status and headers.
res.setHeader('Content-Type', 'application/json') sets one header before the body.
res.write(chunk) sends part of the body. res.end(data) sends the last part and finishes the response. If you never call end, the client waits.
Routing is plain code: look at method and the parsed URL (new URL(req.url, 'http://localhost')) and choose what to send. Frameworks add routing, body parsing and middleware, but nothing magic.
Good habits: always send a status code that matches the result (200, 201, 400, 404, 500), set Content-Type, never throw inside the handler without a try/catch, and listen on port 0 in tests so the system picks a free port.
The server calls itself with fetch, which is built into Node 18 and later. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
/students 200 application/json | [{"id":1,"name":"Asha"},{"id":2,"name":"Ravi"}]
/hello?name=Meera 200 text/plain | Hello Meera
/missing 404 null | Not found
Key points
The handler gets req (readable) and res (writable).
Set status and headers, then end the response.
Routing is a decision on method and path.
Use port 0 in tests to avoid port clashes.
Common mistakes
Forgetting res.end() so the request hangs.
Sending a body without a Content-Type header.
Using req.url as if it were only the path. It includes the query string.
Setting headers after the first write.
Follow-ups
How do you read a JSON request body?
What is the difference between res.write and res.end?
Why does Express exist if http can do this?
Tips
Draw req as a readable stream and res as a writable stream.
Show routing with method and path, to prove it is plain code.
Mention status codes explicitly.
40.nodejs-0040Mediummid
How do you read and validate a JSON request body in a plain Node.js server, and why set a size limit?
The body arrives as chunks on the request stream. Collect the chunks, enforce a maximum size while collecting, then parse the JSON and validate it. A limit protects memory from huge uploads, and clear status codes tell the client what went wrong: 400 for bad JSON, 413 for too large, 415 for the wrong content type.
Full answer
A request body is a stream. A client can send a few bytes or several gigabytes. If you push all chunks into an array without a limit, one malicious or buggy client can use all the memory of the server.
Steps for a safe JSON endpoint:
Check the Content-Type header. If it is not application/json, answer 415.
Read chunks and add up their length. If the total goes above the limit (for example 1 MB), stop reading and answer 413. Check Content-Length for an early rejection, but still count real bytes, because the header can lie or be missing (chunked encoding).
Join the chunks with Buffer.concat and decode once as UTF-8. Decoding each chunk separately can break multi-byte characters.
JSON.parse inside try/catch. A parse error is the client's fault, so answer 400.
Validate the shape (types, ranges, allowed fields) with a schema library or explicit checks. Do not trust parsed JSON.
Answer with a JSON error body that has a stable code.
For file uploads, do not buffer at all. Stream the body to disk or object storage, and set limits on size and time.
Related server settings: requestTimeout and headersTimeout stop slow clients, and a reverse proxy usually adds its own body limit as well.
Each request tests one rule. The limit is 1 KB here so the large case is easy to trigger. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
valid: 201 {"saved":"Asha"}
bad JSON: 400 {"error":"invalid JSON"}
wrong shape: 422 {"error":"name must be text and marks an integer"}
too large: 413 {"error":"body too large"}
wrong type: 415 {"error":"send application/json"}
Key points
Read chunks, count bytes, enforce a limit while reading.
Decode once after joining all chunks.
Use 400, 413 and 415 to explain the failure.
Validate the parsed data. Parsing is not validation.
Common mistakes
Collecting chunks with no size limit.
Calling JSON.parse outside try/catch.
Treating valid JSON as valid data.
Calling chunk.toString() on each chunk separately.
Follow-ups
How would you handle a multipart file upload?
How does a reverse proxy limit body size?
What changes when the client sends Transfer-Encoding: chunked?
Tips
List the status codes in the order they occur.
Say 'parsing is not validation'.
Mention streaming for uploads to show you know when buffering is wrong.