← Interview prep

Node.js interview questions

Event loop, streams, Nest-style APIs, and Node production topics.

200 questions · Page 10 of 10

Want the full pack? Interview packs · Mock interview · Mentora

Page 10 of 10

Questions 181–200 of 200 · 0 of 20 on this page marked learned

181.nodejs-0181Hardsenior

A Node.js process is killed with 'JavaScript heap out of memory' or exit code 137. How do you find out why, and what are the fixes?

There are two different kills. 'JavaScript heap out of memory' (SIGABRT) means V8 reached its own heap limit, which --max-old-space-size controls. Exit code 137 in a container means the operating system or the orchestrator killed the process with SIGKILL because the whole process (heap, Buffers, native memory) went over the container limit. Find out which one it is, then look for growth with heap snapshots, and fix leaks or unbounded data before raising limits.

Full answer

Two different failures

  • V8 heap limit: the old space is full and garbage collection cannot free enough. Node prints FATAL ERROR ... JavaScript heap out of memory and aborts (SIGABRT). The limit depends on the version and the machine and can be set with --max-old-space-size=MB (in a container, set it to about 75 percent of the memory limit).
  • Container OOM kill: the kernel kills the process with SIGKILL when the memory of the whole process (heap, Buffers, native addons, thread stacks) exceeds the cgroup limit. Exit code 137 (128 + 9) and 'OOMKilled' in the orchestrator. No JavaScript error appears. Buffers and external memory are outside the V8 heap, so the heap can look healthy while the container dies.

Investigation

  1. Read process.memoryUsage(): heapUsed, external, arrayBuffers and rss. Which one grows?
  2. Is the growth steady (a leak) or a spike (a huge request, reading a whole file, a big query result)? Look at memory against traffic and deploys.
  3. Take heap snapshots at two times (v8.writeHeapSnapshot(), or node --heapsnapshot-near-heap-limit=N to capture one before the crash) and compare them in Chrome DevTools: look for objects that only increase, such as Maps, arrays and closures.
  4. Typical causes: unbounded caches or Maps, listeners added per request, global arrays used as logs, request data captured in closures or timers, reading whole files and uploads into memory, and large JSON.parse.

Fixes

  • Bound caches (LRU with a maximum size and TTL), remove listeners, stream large data, paginate queries, apply backpressure, and limit request body size.
  • Raise --max-old-space-size or the container memory only after the cause is understood.
  • Alert on memory growth, not only on a crash.
javascript
const { spawnSync } = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');

const runNode = (flags, code, cwd) => spawnSync(process.execPath, [...flags, '-e', code], { encoding: 'utf8', cwd });
const heapLimitMB = (flags) => Number(runNode(flags, "console.log(Math.round(require('v8').getHeapStatistics().heap_size_limit / 1048576))").stdout);

// 1. The V8 limit follows the flag.
const defaultLimit = heapLimitMB([]);
const smallLimit = heapLimitMB(['--max-old-space-size=48']);
console.log('1. limit with --max-old-space-size=48 is lower than the default:', smallLimit < defaultLimit);

// 2. An unbounded array fills the heap and the process aborts.
const leak = "const keep = []; for (;;) keep.push(new Array(10000).fill(Math.random()));";
const crashed = runNode(['--max-old-space-size=48'], leak);
console.log('2. leak crashed with signal :', crashed.signal, '| message mentions heap out of memory:', /heap out of memory/.test(crashed.stderr));

// 3. A bounded buffer, same work, no crash.
const bounded = "const keep = []; for (let i = 0; i < 3000; i++) { keep.push(new Array(10000).fill(i)); if (keep.length > 20) keep.shift(); } console.log('done');";
const fixed = runNode(['--max-old-space-size=48'], bounded);
console.log('3. bounded version          : exit', fixed.status, fixed.stdout.trim());

// 4. Ask Node to write a heap snapshot before it dies.
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'oom-'));
runNode(['--max-old-space-size=48', '--heapsnapshot-near-heap-limit=1'], leak, dir);
console.log('4. snapshot file written near the limit:', fs.readdirSync(dir).some((name) => name.endsWith('.heapsnapshot')));
fs.rmSync(dir, { recursive: true, force: true });

Child processes with a 48 MB heap limit are used so that the crash is quick. Never run a leak on a shared server. The heap snapshot step can take a few seconds. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): 1. limit with --max-old-space-size=48 is lower than the default: true 2. leak crashed with signal : SIGABRT | message mentions heap out of memory: true 3. bounded version : exit 0 done 4. snapshot file written near the limit: true

Key points

  • V8 heap out of memory and container OOM kill are different failures.
  • --max-old-space-size sets the V8 limit; keep it below the container limit.
  • Buffers and native memory are outside the V8 heap.
  • Compare heap snapshots over time to find what grows.
  • Bound caches and stream large data before raising limits.

Common mistakes

  • Raising the memory limit and calling the incident closed.
  • Setting --max-old-space-size above the container limit.
  • Looking only at heapUsed while Buffers and native memory grow.
  • Taking a heap snapshot on a busy production instance without isolating it.
  • Not bounding caches and Maps that are keyed by user input.

Follow-ups

  • How do you tell a leak from a traffic spike in the graphs?
  • What is the difference between rss, heapUsed and external?
  • How do you set the heap size inside a Docker image?

Tips

  • Split the two kinds of kill first.
  • Say 'compare two snapshots'.
  • Mention bounding caches.
182.nodejs-0182Mediummid

What causes ECONNRESET and 'socket hang up' in Node.js HTTP clients, and how do you handle them safely, including keep-alive races?

ECONNRESET means the other side closed or reset the TCP connection while you were using it. Common causes: the server crashed or restarted, a proxy or load balancer idle timeout closed a keep-alive connection that the client then reused, or the server destroyed the socket. Handle it by keeping server keep-alive timeouts longer than proxy idle timeouts, retrying only idempotent requests with backoff, and using timeouts and a limited agent pool.

Full answer

What it means

  • 'socket hang up' with code ECONNRESET: the connection ended before a full response arrived. The peer sent a TCP reset or closed the socket.

Common causes

  • Keep-alive race: the client reuses an idle pooled connection at the same moment the server (or a load balancer) closes it. The request is lost. Fix by making the idle timeout of the server larger than that of the proxy in front of it (for example server.keepAliveTimeout above the load balancer timeout), and the client idle timeout smaller than the server one.
  • The server process crashed, restarted during a deploy, or ran out of memory.
  • A proxy, firewall or NAT dropped long idle connections.
  • The server destroyed the socket on purpose (request too large, protocol error, rate limiting).
  • A client abort. Check whether you aborted the request yourself.

Handling

  • Always attach an error handler, set request timeouts (AbortSignal.timeout), and use an Agent with keepAlive and a maximum number of sockets.
  • Retry only when it is safe: GET, HEAD, PUT and DELETE are idempotent by definition. A POST that reset may or may not have been processed, so retry it only with an idempotency key.
  • Use exponential backoff with jitter and a retry limit, and do not retry on every error code.
  • Graceful shutdown on the server (stop accepting, finish in-flight requests, then exit) prevents resets during deploys.
  • Log the code, syscall, target host and whether the connection was reused, to find patterns.
javascript
const http = require('node:http');

let resetsLeft = 0;
const server = http.createServer((req, res) => {
  if (resetsLeft > 0) { resetsLeft--; req.socket.destroy(); return; }       // the server drops the connection
  res.end(`${req.method} handled`);
}).listen(0, '127.0.0.1', main);

const agent = new http.Agent({ keepAlive: true, maxSockets: 4 });
const send = (method) => new Promise((resolve, reject) => {
  const req = http.request({ port: server.address().port, host: '127.0.0.1', method, agent, timeout: 2000 }, (res) => {
    let text = '';
    res.on('data', (c) => (text += c));
    res.on('end', () => resolve(text));
  });
  req.on('error', reject);
  req.end();
});

const IDEMPOTENT = new Set(['GET', 'HEAD', 'PUT', 'DELETE']);
async function sendWithRetry(method, attempts = 3) {
  for (let attempt = 1; ; attempt++) {
    try { return `${await send(method)} after ${attempt} attempt(s)`; }
    catch (err) {
      const retryable = err.code === 'ECONNRESET' && IDEMPOTENT.has(method) && attempt < attempts;
      if (!retryable) throw err;
      await new Promise((r) => setTimeout(r, 10 * 2 ** attempt));          // backoff (add jitter in real code)
    }
  }
}

async function main() {
  console.log('server.keepAliveTimeout default:', server.keepAliveTimeout, 'ms');

  resetsLeft = 1;
  await send('GET').catch((err) => console.log('1. plain GET     :', err.code, '-', err.message));

  resetsLeft = 1;
  console.log('2. GET with retry:', await sendWithRetry('GET'));

  resetsLeft = 1;
  await sendWithRetry('POST').catch((err) => console.log('3. POST          : not retried,', err.code));

  agent.destroy();
  server.close();
}

A server that destroys one socket makes the reset predictable. Real keep-alive races depend on timing and cannot be reproduced reliably in a short script, so that cause is described in the text only. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): server.keepAliveTimeout default: 5000 ms 1. plain GET : ECONNRESET - socket hang up 2. GET with retry: GET handled after 2 attempt(s) 3. POST : not retried, ECONNRESET

Key points

  • ECONNRESET means the peer closed or reset the connection.
  • Keep-alive reuse races with idle timeouts are a classic cause.
  • The server idle timeout should be longer than the proxy idle timeout.
  • Retry only idempotent requests, with backoff and a limit.
  • Graceful shutdown avoids resets during deploys.

Common mistakes

  • Retrying every failed POST and creating duplicate orders.
  • Retrying immediately in a tight loop with no backoff.
  • No timeouts, so a half-open socket waits for minutes.
  • A proxy idle timeout that is longer than the server keep-alive timeout.
  • Exiting the server process on deploy without draining requests.

Follow-ups

  • How does an idempotency key make a POST retry safe?
  • What is the difference between ECONNRESET and ECONNREFUSED?
  • How should keepAliveTimeout relate to a load balancer idle timeout?

Tips

  • Name the keep-alive race.
  • Say 'retry only when safe'.
  • Mention graceful shutdown.
183.nodejs-0183Mediummid

What does the EMFILE error mean in Node.js, and how do you fix and prevent it?

EMFILE means the process hit its limit of open file descriptors. Sockets, files, pipes and watchers all use descriptors. Causes are opening many files at once without a limit, leaking handles that are never closed, or too many connections for a low ulimit. Fix it by limiting concurrency, always closing handles (finally, pipeline), and raising the ulimit when the real need is higher.

Full answer

What happens

  • Every open file, socket, pipe and watcher uses a file descriptor. The operating system gives each process a limit (ulimit -n, commonly 1024 on some systems, much higher in many containers). Over the limit, calls fail with EMFILE (too many open files in this process). ENFILE is the system-wide version.
  • A web server uses one descriptor per client connection, so a low limit also limits concurrent connections.

Causes

  1. Unbounded concurrency: Promise.all over thousands of file reads or requests opens them all at once.
  2. Leaks: files, streams or sockets that are not closed on error paths. fs.promises.open handles need close() (use try/finally or await using, and use pipeline for streams).
  3. File watchers on large trees (each watcher can use descriptors).
  4. A low ulimit for a busy server, or child processes that inherit descriptors.

Fix and prevent

  • Limit concurrency with a promise pool, p-limit or a queue. This is the main fix.
  • Close handles in finally blocks and on every error path.
  • Reuse connections with a keep-alive Agent instead of one socket per request.
  • graceful-fs (used by npm tools) queues operations and retries after EMFILE.
  • Raise the limit (ulimit -n, systemd LimitNOFILE, Docker --ulimit nofile) when the load really needs it, and monitor open descriptors (ls /proc/PID/fd on Linux, or the diagnostic report).
javascript
const { spawnSync } = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');

const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'emfile-'));
const target = path.join(dir, 'data.txt');
fs.writeFileSync(target, 'hello');

// The child script runs with a low descriptor limit set by the shell.
const child = path.join(dir, 'child.js');
fs.writeFileSync(child, `
const fs = require('node:fs');
const target = process.argv[2];
const COUNT = 200;

async function allAtOnce() {
  const results = await Promise.allSettled(Array.from({ length: COUNT }, () => fs.promises.open(target)));
  const errors = results.filter((r) => r.status === 'rejected').map((r) => r.reason.code);
  await Promise.all(results.filter((r) => r.status === 'fulfilled').map((r) => r.value.close()));
  return { someOpensFailed: errors.length > 0, errorCodes: [...new Set(errors)] };
}

async function withLimit(limit) {
  let next = 0, done = 0;
  async function worker() {
    while (next < COUNT) {
      next++;
      const handle = await fs.promises.open(target);
      try { await handle.readFile('utf8'); done++; } finally { await handle.close(); }
    }
  }
  await Promise.all(Array.from({ length: limit }, worker));
  return done;
}

(async () => {
  console.log('all at once :', JSON.stringify(await allAtOnce()));
  console.log('pool of 10  :', await withLimit(10), 'files read, no errors');
})();
`);

const result = spawnSync('sh', ['-c', `ulimit -n 64; echo "descriptor limit: $(ulimit -n)"; ${JSON.stringify(process.execPath)} ${JSON.stringify(child)} ${JSON.stringify(target)}`], { encoding: 'utf8' });
console.log(result.stdout.trim());
fs.rmSync(dir, { recursive: true });

A shell sets a low descriptor limit (64) for a child process, so the failure is easy to reproduce. How many opens succeed depends on the descriptors that Node already uses, so the first line shows only whether some opens failed and the error codes, not a count. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): descriptor limit: 64 all at once : {"someOpensFailed":true,"errorCodes":["EMFILE"]} pool of 10 : 200 files read, no errors

Key points

  • EMFILE means the process descriptor limit is reached.
  • Unbounded concurrency and leaked handles are the main causes.
  • Limit concurrency with a pool or queue.
  • Close handles on every path.
  • Raise ulimit only when the need is real, and monitor the count.

Common mistakes

  • Using Promise.all over a huge array of file operations.
  • Not closing handles when an error is thrown.
  • Raising the limit without fixing a leak.
  • Watching a huge directory tree with many watchers.
  • Creating a new connection for every outgoing request.

Follow-ups

  • How do you count open descriptors of a running process on Linux?
  • What is the difference between EMFILE and ENFILE?
  • What does graceful-fs do?

Tips

  • Explain that sockets also count.
  • Say 'limit concurrency first, ulimit second'.
  • Mention closing in finally.
184.nodejs-0184Mediummid

Health checks time out while one endpoint runs. How do you confirm that synchronous work is blocking the event loop, and how do you fix it?

One slow synchronous handler blocks every request, including health checks, because JavaScript runs on one thread. Symptoms: high latency for all endpoints, one core at 100 percent CPU, and timeouts on health checks with low database latency. Confirm with event loop delay metrics or a CPU profile, then move the work to the thread pool (async crypto), a worker thread, or another service, or split it into chunks.

Full answer

Symptoms

  • All endpoints get slow at once, not only the heavy one. Health checks fail and the orchestrator restarts healthy-looking instances (which makes things worse).
  • One CPU core is at 100 percent. Database and network latency look normal.
  • Event loop delay (monitorEventLoopDelay) or event loop utilization is high.

Confirming

  • Measure event loop delay in production and alert on p99.
  • Take a CPU profile (node --cpu-prof, or the inspector) and look for a wide synchronous function: a *Sync API, JSON.parse or JSON.stringify of a large object, a regular expression with heavy backtracking, a big loop, template rendering, image processing, or password hashing.

Fixes (choose by the kind of work)

  • Use the async version of an API when one exists. crypto.pbkdf2, scrypt and bcrypt run in the libuv thread pool, so the main thread stays free. Note the pool has 4 threads by default.
  • CPU-heavy JavaScript: move it to a worker thread (a pool such as piscina), or to a separate service or queue.
  • Large data: stream and process in chunks, and yield to the event loop between chunks (setImmediate).
  • Regex: avoid nested quantifiers on user input, set input length limits.
  • Never use *Sync functions in request handlers (they are fine at start-up and in scripts).
  • Keep the health endpoint cheap and separate from heavy work, and set timeouts that avoid restart storms.
javascript
const http = require('node:http');
const crypto = require('node:crypto');

const server = http.createServer((req, res) => {
  if (req.url === '/heavy-sync') {
    crypto.pbkdf2Sync('password', 'salt', 400000, 64, 'sha512');           // blocks the event loop
    res.end('heavy');
  } else if (req.url === '/heavy-async') {
    crypto.pbkdf2('password', 'salt', 400000, 64, 'sha512', () => res.end('heavy'));   // runs in the thread pool
  } else {
    res.end('health');
  }
}).listen(0, '127.0.0.1', async () => {
  const get = (path, order) => new Promise((resolve) => {
    http.get({ port: server.address().port, host: '127.0.0.1', path, agent: false }, (res) => {
      res.resume();
      res.on('end', () => { order.push(path); resolve(); });
    });
  });

  for (const heavy of ['/heavy-sync', '/heavy-async']) {
    const finished = [];
    await Promise.all([get(heavy, finished), get('/health', finished)]);     // heavy is sent first, then the health check
    console.log(heavy.padEnd(13), 'responses finished in this order:', finished.join(', '));
  }
  server.close();
});

Each run sends the heavy request first and then a health check. The order in which the responses finish shows whether the health check had to wait for the heavy work. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): /heavy-sync responses finished in this order: /heavy-sync, /health /heavy-async responses finished in this order: /health, /heavy-async

Key points

  • One thread runs all JavaScript, so sync work blocks everything.
  • Symptoms: high latency everywhere and one core at 100 percent.
  • Measure event loop delay and profile the CPU.
  • Use async APIs, worker threads, chunking, or another service.
  • Do not use *Sync APIs in request handlers.

Common mistakes

  • Using pbkdf2Sync, readFileSync or JSON work inside a request handler.
  • Scaling out instances instead of removing the blocking code.
  • Health checks that share the same slow code path.
  • Assuming async functions always run off the main thread.
  • Increasing the thread pool size to fix a CPU-bound JavaScript loop.

Follow-ups

  • Why does the async version not block the loop?
  • When is a worker thread better than the thread pool?
  • How do you protect against regex denial of service?

Tips

  • Describe symptoms before fixes.
  • Say 'measure loop delay and profile'.
  • Give three fixes by kind of work.
185.nodejs-0185Easyfresher

Which Node.js system error codes should you know (ENOENT, EADDRINUSE, ECONNREFUSED and others), and what does each one mean?

Node errors from the operating system carry a code (such as ENOENT), a syscall name and often a path or address. The common ones: ENOENT (missing path), EEXIST (already exists), EISDIR and ENOTDIR (wrong kind of path), EACCES and EPERM (permission), ENOTEMPTY (directory not empty), EMFILE (too many open files), EADDRINUSE (port taken), ECONNREFUSED (nothing listening), ECONNRESET (connection closed abruptly), ETIMEDOUT (no answer), ENOTFOUND (DNS failed), EPIPE (write to a closed pipe).

Full answer

Check err.code (a string), not the message text. Other useful fields: err.syscall (open, read, listen, connect), err.path, err.address and err.port.

File system

  • ENOENT: the path does not exist. Often a wrong relative path (relative to the process working directory, not to the file).
  • EEXIST: the path already exists (flag wx, mkdir without recursive).
  • EISDIR, ENOTDIR: a directory used as a file, or a file used as a directory.
  • ENOTEMPTY: rmdir on a directory that has content (use fs.rm with recursive).
  • EACCES, EPERM: permission denied by file mode, owner or policy.
  • EMFILE, ENFILE: too many open files (process or system).
  • ENOSPC: the disk is full.

Network

  • EADDRINUSE: another process (or an old instance of yours) already listens on the port.
  • ECONNREFUSED: the host is reachable, but nothing listens on that port (service down or wrong port).
  • ECONNRESET: the connection was closed abruptly by the peer.
  • ETIMEDOUT: no answer within the time limit (firewall, overloaded host).
  • ENOTFOUND (and EAI_AGAIN): the DNS lookup failed or timed out.
  • EPIPE: writing to a connection or pipe that the other side closed.
  • EADDRNOTAVAIL: the address is not valid on this machine.

Handle them by code: ENOENT may be an expected case, ECONNREFUSED and ETIMEDOUT may deserve a retry, EADDRINUSE and EACCES at start-up should stop the process with a clear message.

javascript
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const net = require('node:net');

(async () => {
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'errno-'));
  fs.writeFileSync(path.join(dir, 'file.txt'), 'x');
  const cases = {
    ENOENT: () => fs.promises.readFile(path.join(dir, 'missing.txt')),
    EISDIR: () => fs.promises.readFile(dir),
    EEXIST: () => fs.promises.writeFile(path.join(dir, 'file.txt'), 'y', { flag: 'wx' }),
    ENOTEMPTY: () => fs.promises.rmdir(dir),
    ENOTDIR: () => fs.promises.readFile(path.join(dir, 'file.txt', 'child')),
    EADDRINUSE: () => new Promise((resolve, reject) => {
      const first = net.createServer().listen(0, '127.0.0.1', () => {
        const second = net.createServer().on('error', (e) => { first.close(); reject(e); });
        second.listen(first.address().port, '127.0.0.1');
      });
    }),
    ECONNREFUSED: () => new Promise((resolve, reject) => {
      const probe = net.createServer().listen(0, '127.0.0.1', () => {
        const { port } = probe.address();
        probe.close(() => net.connect(port, '127.0.0.1').on('error', reject));   // nothing listens on that port now
      });
    }),
  };
  const meaning = {
    ENOENT: 'path does not exist', EISDIR: 'a directory was used as a file', EEXIST: 'path already exists',
    ENOTEMPTY: 'directory is not empty', ENOTDIR: 'a path part is not a directory', EADDRINUSE: 'port is already in use',
    ECONNREFUSED: 'nothing is listening there',
  };
  for (const [name, run] of Object.entries(cases)) {
    const err = await run().then(() => ({ code: 'no error' }), (e) => e);
    console.log(name.padEnd(13), err.code === name ? 'matched' : 'got ' + err.code, '|', String(err.syscall).padEnd(8), '|', meaning[name]);
  }
  fs.rmSync(dir, { recursive: true });
})();

Seven of these errors are produced on purpose and the matching code is checked. ENOTFOUND, ETIMEDOUT and EACCES depend on the network or the user, so they were not run. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): ENOENT matched | open | path does not exist EISDIR matched | read | a directory was used as a file EEXIST matched | open | path already exists ENOTEMPTY matched | rmdir | directory is not empty ENOTDIR matched | open | a path part is not a directory EADDRINUSE matched | listen | port is already in use ECONNREFUSED matched | connect | nothing is listening there

Key points

  • Compare err.code, not the message text.
  • Use err.syscall, err.path and err.address for context.
  • Know the file codes: ENOENT, EEXIST, EISDIR, ENOTEMPTY, EACCES, EMFILE.
  • Know the network codes: EADDRINUSE, ECONNREFUSED, ECONNRESET, ETIMEDOUT, ENOTFOUND.
  • Decide per code: expect, retry or fail loudly.

Common mistakes

  • Parsing the error message text instead of using err.code.
  • Treating every ENOENT as a bug even when the file is optional.
  • Retrying EADDRINUSE or EACCES forever at start-up.
  • Using a relative path and getting ENOENT from a different working directory.
  • Swallowing the error and losing the path and syscall.

Follow-ups

  • What is the difference between EACCES and EPERM?
  • Why can ENOTFOUND be temporary?
  • How do you check whether a file exists without a race?

Tips

  • Group the codes into file and network.
  • Say 'use err.code'.
  • Mention what you would do for each.
186.nodejs-0186Easyfresher

Assume this file runs as a CommonJS script in sloppy mode (no 'use strict'). ```js const student = { name: 'Asha', regular() { return this.name; }, arrow: () => this === module.exports, later() { setTimeout(function () { console.log('4', this === student, typeof this); }, 0); setTimeout(() => console.log('5', this.name), 0); }, }; const detached = student.regular; console.log('1', student.regular()); console.log('2', student.arrow()); console.log('3', detached()); student.later(); console.log('6', detached.call({ name: 'Ravi' }), detached.bind({ name: 'Meera' }).call({ name: 'Other' })); ``` What does it print, and why?

The synchronous lines print 1 Asha, 2 true, 3 undefined and 6 Ravi Meera. Then the timers print 4 false object and 5 Asha. A method called as obj.method() gets obj as this. An arrow function takes this from where it was written (the module, whose this is module.exports). A detached method has no object, so this is globalThis in sloppy mode. call and bind set this, and bind wins over a later call. A normal function used as a timer callback gets the Timeout object as this.

Full answer

Line by line:

  • Log 1: student.regular() is called on student, so this is student and it returns Asha.
  • Log 2: arrow is an arrow function. It has no this of its own and uses the this of the module scope, which in a CommonJS file is module.exports. So this === module.exports is true.
  • Log 3: detached is the same function without the object. The call detached() has no receiver. In sloppy mode this becomes globalThis, and globalThis.name is undefined, so the result is undefined. In strict mode this would be undefined and the line would throw a TypeError.
  • student.later() registers two timers and returns.
  • Log 6: detached.call sets this to the given object and returns Ravi. detached.bind({ name: 'Meera' }) creates a new function with this fixed to Meera. Calling it with call({ name: 'Other' }) cannot change it, so it returns Meera.
  • All synchronous lines are done, so the timers fire.
  • Log 4: a function expression passed to setTimeout is called by Node with this set to the Timeout object, not to student. So this === student is false and typeof this is object.
  • Log 5: the arrow function inside later() uses the this of later(), which is student, so it prints Asha.

Order: 1, 2, 3, 6 from the synchronous code, then 4 and 5 from the two timers (same delay, so in the order they were created).

Rules: this depends on how a function is called, except arrow functions, where it depends on where they are written.

javascript
const student = {
  name: 'Asha',
  regular() { return this.name; },
  arrow: () => this === module.exports,
  later() {
    setTimeout(function () { console.log('4', this === student, typeof this); }, 0);
    setTimeout(() => console.log('5', this.name), 0);
  },
};
const detached = student.regular;
console.log('1', student.regular());
console.log('2', student.arrow());
console.log('3', detached());
student.later();
console.log('6', detached.call({ name: 'Ravi' }), detached.bind({ name: 'Meera' }).call({ name: 'Other' }));

The snippet is the puzzle itself. The output is the order of the log lines. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): 1 Asha 2 true 3 undefined 6 Ravi Meera 4 false object 5 Asha

Key points

  • A method call obj.f() sets this to obj.
  • A detached method loses this (globalThis in sloppy mode, undefined in strict mode).
  • Arrow functions use the this of the surrounding scope.
  • bind fixes this permanently; call and apply set it for one call.
  • A timer callback written as a normal function gets the Timeout object.

Common mistakes

  • Thinking that student.arrow() uses student as this.
  • Expecting detached() to throw in sloppy mode.
  • Believing that call can override a bound function.
  • Expecting this inside setTimeout to be the object that registered it.
  • Putting the timer lines before the synchronous lines.

Follow-ups

  • What changes if the file starts with 'use strict'?
  • What is this at the top level of an ES module?
  • How do class methods lose this when passed as callbacks, and how do you fix it?

Tips

  • List the four binding rules.
  • Mention arrow functions separately.
  • Say what strict mode changes.
187.nodejs-0187Mediummid

The wait helper resolves after the given number of milliseconds. Assume that every timer fires on time. ```js const wait = (ms, value) => new Promise((resolve) => setTimeout(resolve, ms, value)); async function main() { const items = [30, 10, 20]; console.log('A'); items.forEach(async (ms) => { await wait(ms); console.log('forEach', ms); }); console.log('B'); await wait(100); for (const ms of items) { await wait(ms); console.log('for-of', ms); } const all = await Promise.all(items.map(async (ms) => { await wait(ms); return ms * 2; })); console.log('all', all); console.log(items.map(async (ms) => ms)); } main(); ``` What does it print, and why?

A and B print first, because forEach does not wait for async callbacks. Then forEach 10, 20, 30 (they all run at the same time and finish by delay). Then for-of 30, 10, 20 because the loop waits for each item in turn. Promise.all with map runs the work at the same time and keeps the input order in its result, [60, 20, 40]. The last line prints an array of promises that are already resolved: [ Promise { 30 }, Promise { 10 }, Promise { 20 } ].

Full answer

Step by step:

  1. A is printed. forEach calls the async callback for each item. Every callback runs until its first await and returns a promise that forEach ignores. forEach returns immediately.
  2. B is printed. Then main waits 100 ms. During that time the three timers (30, 10 and 20 ms) fire in order of delay, so the output is forEach 10, forEach 20, forEach 30. forEach started all three at once, which is why the order follows the delays and not the array order.
  3. The for-of loop uses await inside the loop body, so each iteration waits before the next starts. The output follows array order: for-of 30, for-of 10, for-of 20. The total time is 60 ms (sequential).
  4. items.map(async ...) creates three promises at once, so the waits overlap (about 30 ms in total). Promise.all collects the results in the same order as the input array, not in the order of completion: [ 60, 20, 40 ].
  5. The last map has async functions that do not await anything. Each call returns a promise that is already resolved, and console.log shows them as Promise { 30 }, Promise { 10 }, Promise { 20 }. It does not show the plain numbers.

Lessons: use for-of when work must run in order, Promise.all with map when work can run in parallel, and never use forEach with async callbacks, because errors and completion are lost. For limited parallelism use a pool.

javascript
const wait = (ms, value) => new Promise((resolve) => setTimeout(resolve, ms, value));

async function main() {
  const items = [30, 10, 20];
  console.log('A');
  items.forEach(async (ms) => { await wait(ms); console.log('forEach', ms); });
  console.log('B');
  await wait(100);

  for (const ms of items) { await wait(ms); console.log('for-of', ms); }

  const all = await Promise.all(items.map(async (ms) => { await wait(ms); return ms * 2; }));
  console.log('all', all);
  console.log(items.map(async (ms) => ms));
}
main();

The snippet is the puzzle itself. The timers are 100 ms apart from the next stage, so the order is stable. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): A B forEach 10 forEach 20 forEach 30 for-of 30 for-of 10 for-of 20 all [ 60, 20, 40 ] [ Promise { 30 }, Promise { 10 }, Promise { 20 } ]

Key points

  • forEach ignores the promises returned by async callbacks.
  • await inside for-of makes iterations sequential.
  • map with Promise.all runs in parallel and keeps input order in the result.
  • An async function always returns a promise.
  • Use a pool when you need parallel work with a limit.

Common mistakes

  • Expecting forEach to wait before main continues.
  • Thinking Promise.all returns results in the order they finish.
  • Expecting console.log of async function results to show numbers.
  • Using await in a loop when the calls are independent.
  • Using Promise.all for thousands of items with no limit.

Follow-ups

  • How do you run these tasks with at most two at a time?
  • What does Promise.allSettled return?
  • How does error handling differ between forEach and for-of?

Tips

  • Compare the three loops in one table.
  • Mention input order in Promise.all.
  • Say how you would limit concurrency.
188.nodejs-0188Easyfresher

Assume this file runs as a CommonJS script in sloppy mode. ```js console.log(typeof hoisted, typeof notHoisted); function hoisted() {} var notHoisted = function () {}; try { console.log(a); } catch (e) { console.log(e.name); } let a = 1; console.log(b); var b = 2; { function inBlock() { return 'block'; } } console.log(typeof inBlock); var x = 'outer'; (function () { console.log(x); var x = 'inner'; })(); try { new K(); } catch (e) { console.log(e.name); } class K {} console.log(typeof K); ``` What does it print, and why?

It prints: function undefined, ReferenceError, undefined, function, undefined, ReferenceError, function. Function declarations are hoisted with their body. var is hoisted as undefined. let and class exist but cannot be used before their line (the temporal dead zone), so they throw a ReferenceError. A var inside a function shadows the outer variable for the whole function, so the early read gives undefined. In sloppy mode a function declared in a block is also visible outside the block.

Full answer

Each line, in order:

  1. typeof hoisted is function, because the whole declaration is hoisted. typeof notHoisted is undefined: the var is hoisted and set to undefined, and the function is assigned later at its line. Output: function undefined.
  2. console.log(a) happens before let a = 1. The binding exists but is in the temporal dead zone, so reading it throws a ReferenceError. The catch prints ReferenceError.
  3. console.log(b) prints undefined. The var b is hoisted and initialised with undefined, and 2 is assigned later.
  4. inBlock is declared inside a block. In sloppy mode (the old web-compatible rule) the function is also available in the surrounding function scope after the block runs, so typeof inBlock is function. In strict mode it would be undefined.
  5. Inside the function, var x is hoisted to the top of that function and shadows the outer x. At the time of the log it is still undefined, so it prints undefined, not outer.
  6. new K() before the class line throws a ReferenceError, because class declarations are also in the temporal dead zone.
  7. After the class line, typeof K is function (a class is a function).

Rules: function declarations hoist with their value, var hoists as undefined, let, const and class hoist but stay uninitialised until their line. Reading them early is an error, even with typeof.

javascript
console.log(typeof hoisted, typeof notHoisted);
function hoisted() {}
var notHoisted = function () {};

try { console.log(a); } catch (e) { console.log(e.name); }
let a = 1;

console.log(b);
var b = 2;

{ function inBlock() { return 'block'; } }
console.log(typeof inBlock);

var x = 'outer';
(function () { console.log(x); var x = 'inner'; })();

try { new K(); } catch (e) { console.log(e.name); }
class K {}
console.log(typeof K);

The snippet is the puzzle itself. The output is one line per console.log call. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): function undefined ReferenceError undefined function undefined ReferenceError function

Key points

  • Function declarations are hoisted with their body.
  • var is hoisted and initialised to undefined.
  • let, const and class are in the temporal dead zone until their line.
  • A var in a function shadows outer variables for the whole function.
  • Block functions behave differently in sloppy and strict mode.

Common mistakes

  • Thinking let is not hoisted at all.
  • Expecting the var function expression to be callable before its line.
  • Expecting the early log of x to print outer.
  • Thinking typeof is always safe, even in the dead zone.
  • Mixing up sloppy and strict mode results for block functions.

Follow-ups

  • What does strict mode change in this file?
  • What does a function declaration inside a block do in an ES module?
  • How does the TDZ help find bugs?

Tips

  • List the three kinds of hoisting.
  • Say 'temporal dead zone'.
  • Mention sloppy versus strict mode.
189.nodejs-0189Hardsenior

This file uses an async generator that has a finally block. Assume that it runs as a CommonJS script. ```js async function* gen() { try { console.log('start'); yield 1; yield 2; yield 3; } finally { console.log('cleanup'); } } (async () => { for await (const v of gen()) { console.log('got', v); if (v === 2) break; } const g = gen(); console.log('created'); console.log(await g.next()); console.log(await g.return('early')); console.log(await g.next()); for await (const v of [Promise.resolve('a'), 'b', wait('c')]) console.log(v); const h = gen(); const [p1, p2] = [h.next(), h.next()]; console.log((await p1).value, (await p2).value); await h.return(); })(); function wait(v) { return new Promise((r) => setTimeout(r, 10, v)); } ``` What does it print, and why?

The output is: start, got 1, got 2, cleanup, created, start, { value: 1, done: false }, cleanup, { value: 'early', done: true }, { value: undefined, done: true }, a, b, c, start, 1 2, cleanup. A generator body starts on the first next(), leaving a for await loop with break calls return(), which runs finally, return() on a started generator runs finally and finishes it, and calls to next() made without awaiting are queued and answered in order.

Full answer

Walk through each part:

  1. First loop: gen() creates the generator but does not run it. The first next() from for await starts the body, which prints start and yields 1 (got 1), then 2 (got 2). The break calls the generator's return() method. That resumes the generator at the yield and runs the finally block, so cleanup is printed before the loop is finished.
  2. const g = gen(); console.log('created'): no start yet. Creating an async generator does not run any of its code.
  3. await g.next() starts the body: start is printed and the result is { value: 1, done: false }.
  4. await g.return('early') resumes the generator with a return completion. The finally block runs (cleanup) and the result is { value: 'early', done: true }.
  5. Another next() on a finished generator gives { value: undefined, done: true } and prints nothing.
  6. for await over an array with a promise, a plain value and a promise that resolves later: for await awaits each item, so it prints a, b, c.
  7. h.next() is called twice without waiting. An async generator keeps a queue of requests and answers them in order. The first call starts the body (start), so the output is start and then 1 2 from the log. The final h.return() finishes the generator and runs cleanup.

Remember: finally in a generator runs when the consumer leaves early with break, return or throw, as long as the generator was started. If a generator was never started, return() does not run its body, so there is nothing to clean up.

javascript
async function* gen() {
  try { console.log('start'); yield 1; yield 2; yield 3; }
  finally { console.log('cleanup'); }
}

(async () => {
  for await (const v of gen()) { console.log('got', v); if (v === 2) break; }

  const g = gen();
  console.log('created');
  console.log(await g.next());
  console.log(await g.return('early'));
  console.log(await g.next());

  for await (const v of [Promise.resolve('a'), 'b', wait('c')]) console.log(v);

  const h = gen();
  const [p1, p2] = [h.next(), h.next()];
  console.log((await p1).value, (await p2).value);
  await h.return();
})();
function wait(v) { return new Promise((r) => setTimeout(r, 10, v)); }

The snippet is the puzzle itself. The output is the order of the log lines. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): start got 1 got 2 cleanup created start { value: 1, done: false } cleanup { value: 'early', done: true } { value: undefined, done: true } a b c start 1 2 cleanup

Key points

  • The body of a generator starts at the first next(), not at the call.
  • break in for await calls return(), which runs finally.
  • return() on a started generator runs finally and completes it.
  • Queued next() calls are answered in order.
  • for await also works on iterables of promises and plain values.

Common mistakes

  • Expecting start to print when gen() is called.
  • Expecting cleanup to be skipped on break.
  • Thinking an already finished generator throws on next().
  • Thinking for await requires an async iterable only.
  • Forgetting that the 10 ms timer for c does not change the order.

Follow-ups

  • What happens if the consumer throws inside the for await body?
  • How does an async generator relate to a Readable stream?
  • Why do streams need cleanup logic like finally?

Tips

  • Say 'lazy until the first next'.
  • Mention break calling return.
  • Explain the request queue.
190.nodejs-0190Mediummid

This file mixes async functions, promise chains and an unhandledRejection listener. Assume it runs with node app.js on a current Node.js version. ```js process.on('unhandledRejection', (reason) => console.log('unhandledRejection:', reason.message)); async function fails(label) { throw new Error(label); } async function main() { try { fails('not awaited'); } catch (e) { console.log('caught 1'); } try { return fails('returned'); } catch (e) { console.log('caught 2'); } } main().catch((e) => console.log('outer caught:', e.message)); Promise.reject(new Error('p1')) .catch((e) => { console.log('catch', e.message); throw new Error('p2'); }) .catch((e) => console.log('catch', e.message)) .then(() => console.log('then runs')); Promise.reject(new Error('x')) .finally(() => console.log('finally')) .catch((e) => console.log('after finally:', e.message)); console.log('sync end'); ``` What does it print, and why?

The output is: sync end, catch p1, finally, catch p2, outer caught: returned, then runs, after finally: x, unhandledRejection: not awaited. The messages caught 1 and caught 2 never print. A rejected promise that is not awaited is not caught by try/catch, and return without await skips the catch block of the same function. The unhandledRejection event fires after the microtasks finish.

Full answer

Synchronous part:

  • main() starts. fails('not awaited') returns a rejected promise that nobody awaits. try/catch only catches errors from await, so caught 1 never prints. That promise stays unhandled.
  • Then return fails('returned') returns the rejected promise without await. The function finishes before the rejection is handled, so the catch block does not run (caught 2 never prints). main's own promise follows the rejected promise and will be rejected.
  • The two promise chains are set up, and sync end is printed first.

Microtasks, in rounds:

  • Round 1: catch p1 (the first catch handler runs and throws p2), finally (the finally callback of the second chain runs).
  • Round 2: the second catch in the first chain handles p2 and prints catch p2.
  • Later rounds: main's promise needs a few extra rounds to adopt the rejected promise, so outer caught: returned is printed next, followed by then runs (the first chain recovers after catch). The finally chain also needs extra rounds to pass the original rejection on, so after finally: x comes after them.

After the microtask queue is empty, Node checks for rejections with no handler. The promise from fails('not awaited') is still unhandled, so the unhandledRejection listener prints its message last. Without the listener, Node 15 and later would crash the process with an error.

Lessons: always await or return and handle promises, use return await inside try when you want to catch the error there, and treat unhandled rejections as bugs. Exact order of the middle lines depends on the number of microtask hops, which is why you should not rely on it in real code.

javascript
process.on('unhandledRejection', (reason) => console.log('unhandledRejection:', reason.message));

async function fails(label) { throw new Error(label); }

async function main() {
  try { fails('not awaited'); } catch (e) { console.log('caught 1'); }
  try { return fails('returned'); } catch (e) { console.log('caught 2'); }
}
main().catch((e) => console.log('outer caught:', e.message));

Promise.reject(new Error('p1'))
  .catch((e) => { console.log('catch', e.message); throw new Error('p2'); })
  .catch((e) => console.log('catch', e.message))
  .then(() => console.log('then runs'));

Promise.reject(new Error('x'))
  .finally(() => console.log('finally'))
  .catch((e) => console.log('after finally:', e.message));

console.log('sync end');

The snippet is the puzzle itself. The output is the order of the log lines. The ordering of the middle lines follows the number of promise steps, and the output shown comes from one run on Node.js v24.22.1. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): sync end catch p1 finally catch p2 outer caught: returned then runs after finally: x unhandledRejection: not awaited

Key points

  • try/catch catches only awaited rejections.
  • return without await skips the catch of the same function.
  • A catch that throws passes a new error to the next catch.
  • finally passes the original result or error on.
  • Unhandled rejections are reported after microtasks drain, and crash Node by default.

Common mistakes

  • Expecting the catch block to run for a promise that was not awaited.
  • Using return promise inside try and expecting catch to work.
  • Thinking finally can swallow the error.
  • Ignoring unhandledRejection warnings.
  • Relying on the exact order of unrelated promise chains.

Follow-ups

  • What changes if main used return await fails('returned')?
  • What does the default unhandled rejection mode do in Node 15 and later?
  • How can you detect floating promises with a linter?

Tips

  • Explain the two missed catches first.
  • Say that the middle order depends on microtask hops.
  • Mention return await.
191.nodejs-0191Easyfresher

Implement promisify from scratch: how does it turn a Node-style callback function into a function that returns a promise?

promisify wraps a function whose last argument is an error-first callback (err, value). The wrapper returns a promise, calls the original with the same arguments plus its own callback, rejects when err is set, and resolves with the value otherwise. Keep this, catch synchronous throws (the Promise constructor does this for you), and honour util.promisify.custom for functions that already have a promise version.

Full answer

The contract of a Node-style function: the last argument is a callback, called once as callback(err, result). Success passes null or undefined as err.

Steps

  1. Return a new function that keeps this (use a normal function, not an arrow function) and collects the arguments.
  2. Return new Promise((resolve, reject) => ...). Inside, call the original function with the arguments plus a callback.
  3. In the callback: if err is truthy, reject(err). Otherwise resolve(value).
  4. Some callbacks pass more than one result, for example (err, a, b). util.promisify resolves with only the first value unless the function defines util.promisify.custom. A simple version can resolve with an array when there is more than one value.
  5. If the original throws synchronously, the Promise executor turns it into a rejection, so the caller never sees a sync exception.
  6. Respect util.promisify.custom: if the function has that symbol property, return it, so that functions like setTimeout (which has a custom version) and fs.exists work as expected.

Limits: the callback must be called exactly once. Functions that call the callback twice, or that are event based (streams), are not suitable. Prefer the built-in util.promisify and the fs/promises family in real code.

javascript
const util = require('node:util');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');

function promisify(fn) {
  if (typeof fn !== 'function') throw new TypeError('fn must be a function');
  if (typeof fn[util.promisify.custom] === 'function') return fn[util.promisify.custom];
  return function (...args) {
    return new Promise((resolve, reject) => {
      fn.call(this, ...args, (err, ...values) => {
        if (err) reject(err);
        else resolve(values.length > 1 ? values : values[0]);
      });
    });
  };
}

(async () => {
  const file = path.join(os.tmpdir(), 'promisify-demo.txt');
  fs.writeFileSync(file, 'hello');

  console.log('1.', await promisify(fs.readFile)(file, 'utf8'));
  console.log('2.', await promisify(fs.readFile)(file + '.missing').catch((e) => e.code));

  const calculator = { base: 10, add(x, cb) { setImmediate(() => cb(null, this.base + x)); } };
  calculator.addAsync = promisify(calculator.add);
  console.log('3. this is kept:', await calculator.addAsync(5));

  const pair = (cb) => cb(null, 'a', 'b');
  console.log('4. two values:', await promisify(pair)());

  const throwsNow = () => { throw new Error('sync failure'); };
  console.log('5.', await promisify(throwsNow)().catch((e) => e.message));

  console.log('6. custom version used:', promisify(setTimeout) === setTimeout[util.promisify.custom]);
  fs.unlinkSync(file);
})();

Each numbered line checks one rule of the contract on the real fs module and small test functions. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): 1. hello 2. ENOENT 3. this is kept: 15 4. two values: [ 'a', 'b' ] 5. sync failure 6. custom version used: true

Key points

  • Return a promise and call the original with an added callback.
  • Reject on err, resolve on the value.
  • Keep this by using a normal function.
  • The Promise executor turns a sync throw into a rejection.
  • Use util.promisify in real code.

Common mistakes

  • Using an arrow function and losing this.
  • Forgetting that the callback can receive several values.
  • Promisifying a function that calls its callback more than once.
  • Not rejecting when err is a falsy but meaningful value such as 0 (rare, but check for null or undefined).
  • Writing your own version when fs/promises already exists.

Follow-ups

  • How would you write the reverse, callbackify?
  • What does util.promisify.custom do?
  • Why is the Promise constructor safe against synchronous throws?

Tips

  • State the callback contract first.
  • Mention this and multiple values.
  • Say that you would use the built-in version.
192.nodejs-0192Easyfresher

Implement debounce and throttle. What is the difference, and when do you use each?

Debounce waits until calls stop for a given time, then runs once with the last arguments (search box typing, resize end). Throttle runs at most once per interval while calls keep coming (scroll handlers, progress updates, rate-limited work). Both are closures around a timer. Add cancel (and flush for debounce) so the timers can be cleaned up.

Full answer

Debounce

  • Keep a timer id in a closure. On every call, clear the old timer and start a new one. Only when the quiet period passes does the function run, with the arguments of the last call.
  • Option leading: run on the first call and ignore the rest until the quiet period ends.
  • Add cancel() to clear the timer, so a pending call does not run after shutdown or unmount.

Throttle

  • Allow a call, then ignore calls until the interval has passed. A common version runs the first call at once (leading) and, if calls came in during the wait, runs the last one at the end of the interval (trailing), so the final state is not lost.
  • It limits the rate of calls, but does not delay a single call.

Choosing

  • Debounce: you care about the final value after a burst (autosave after typing, search suggestions).
  • Throttle: you care about regular updates during a burst (logging progress, scroll or mouse move).

Testing: inject a clock (setTimeout, clearTimeout and now) so tests do not sleep. Real code in Node can use timers with unref() so a pending timer does not keep the process alive.

javascript
// A small fake clock, so the example does not need to wait.
function createClock() {
  let now = 0, nextId = 1; const timers = new Map();
  return {
    now: () => now,
    setTimeout(fn, ms) { const id = nextId++; timers.set(id, { at: now + ms, fn }); return id; },
    clearTimeout(id) { timers.delete(id); },
    advance(ms) {
      const target = now + ms;
      for (;;) {
        const due = [...timers].filter(([, t]) => t.at <= target).sort((a, b) => a[1].at - b[1].at)[0];
        if (!due) break;
        now = due[1].at; timers.delete(due[0]); due[1].fn();
      }
      now = target;
    },
  };
}

function debounce(fn, wait, { leading = false, clock = globalThis } = {}) {
  let timer, lastArgs;
  function debounced(...args) {
    lastArgs = args;
    const callNow = leading && timer === undefined;
    clock.clearTimeout(timer);
    timer = clock.setTimeout(() => { timer = undefined; if (!leading) fn.apply(this, lastArgs); }, wait);
    if (callNow) fn.apply(this, args);
  }
  debounced.cancel = () => { clock.clearTimeout(timer); timer = undefined; };
  return debounced;
}

function throttle(fn, interval, { clock = globalThis } = {}) {
  let last = -Infinity, timer, pendingArgs;
  function throttled(...args) {
    const wait = interval - (clock.now() - last);
    if (wait <= 0) { last = clock.now(); fn.apply(this, args); return; }
    pendingArgs = args;                                          // keep the latest call for the trailing run
    timer ??= clock.setTimeout(() => { timer = undefined; last = clock.now(); fn.apply(this, pendingArgs); }, wait);
  }
  throttled.cancel = () => { clock.clearTimeout(timer); timer = undefined; };
  return throttled;
}

const clock = createClock();

const saved = [];
const save = debounce((text) => saved.push(text), 100, { clock });
save('h'); clock.advance(30); save('he'); clock.advance(30); save('hel');
console.log('debounce: before the quiet period:', JSON.stringify(saved));
clock.advance(100);
console.log('debounce: after the quiet period :', JSON.stringify(saved));

const leadingCalls = [];
const leading = debounce((x) => leadingCalls.push(x), 100, { leading: true, clock });
leading('a'); leading('b'); leading('c');
console.log('debounce leading                 :', JSON.stringify(leadingCalls));

const ticks = [];
const log = throttle((x) => ticks.push(`${x}@${clock.now()}`), 100, { clock });
const start = clock.now();
for (let i = 0; i < 10; i++) { log(i); clock.advance(30); }
clock.advance(100);
console.log('throttle over 300 ms (10 calls)  :', ticks.map((t) => t.replace(/@(\d+)/, (m, n) => '@+' + (n - start))).join(', '));

A fake clock makes the timing exact, so every run prints the same result. The real setTimeout would give the same logic with small timing variations. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): debounce: before the quiet period: [] debounce: after the quiet period : ["hel"] debounce leading : ["a"] throttle over 300 ms (10 calls) : 0@+0, 3@+100, 6@+200, 9@+300

Key points

  • Debounce runs after calls stop; throttle runs at most once per interval.
  • Both use a closure with timer state.
  • Debounce uses the last arguments.
  • Throttle often has leading and trailing calls.
  • Provide cancel and test with a fake clock.

Common mistakes

  • Creating the debounced function inside a render or request handler, so state is never shared.
  • Losing this or the arguments.
  • Using throttle when only the final value matters.
  • Leaving timers pending after shutdown.
  • Mixing up the two names in an explanation.

Follow-ups

  • How would you add a maxWait option to debounce?
  • How does lodash implement leading and trailing?
  • How do you test timer code without waiting?

Tips

  • Use a one-line definition for each.
  • Give one use case each.
  • Mention cancel and a fake clock.
193.nodejs-0193Mediummid

Implement a small EventEmitter from scratch: on, once, off, emit, and the special 'error' event. What details do people forget?

An emitter stores arrays of listeners by event name. emit calls each listener synchronously with the arguments and with this set to the emitter, and returns whether any listener existed. once wraps the listener so it removes itself before running. Details that people forget: copy the array before calling (so removal during emit is safe), let off find a once wrapper by the original function, and throw when 'error' is emitted with no listener.

Full answer

Data model: a Map from event name to an array of listener entries. An entry holds the function to call and the original function (they differ for once).

Methods

  • on(event, fn): push the listener and return this, so calls can be chained.
  • prependListener(event, fn): same, but at the start of the array.
  • once(event, fn): register a wrapper that first removes itself, then calls fn. Store fn as the original so off(event, fn) works before the event fires.
  • off(event, fn): remove the first entry whose function or original equals fn. Delete the key when the array is empty to avoid leaks.
  • emit(event, ...args): take a copy of the listeners, call each with this as the emitter, and return true when at least one listener existed. Calls are synchronous and in registration order.
  • listenerCount(event).

Details

  • Copy before looping. A once wrapper (or any listener) that removes itself during emit would shift the array and skip the next listener.
  • The special event 'error': if nobody listens, emit('error', err) must throw the error (or wrap it), because swallowing it hides failures.
  • Exceptions inside a listener stop the loop in the built-in emitter. Document the behaviour you choose.
  • Memory: listeners that are never removed are a classic leak. Node warns when more than 10 listeners are added to one event (setMaxListeners).
  • Listeners are synchronous. If you need async handling, use events.once or the async iterator (events.on).
javascript
class Emitter {
  #events = new Map();

  #add(event, entry, prepend) {
    const list = this.#events.get(event) ?? [];
    prepend ? list.unshift(entry) : list.push(entry);
    this.#events.set(event, list);
    return this;
  }
  on(event, fn) { return this.#add(event, { fn, original: fn }, false); }
  prependListener(event, fn) { return this.#add(event, { fn, original: fn }, true); }
  once(event, fn) {
    const wrapper = (...args) => { this.off(event, fn); return fn.apply(this, args); };
    return this.#add(event, { fn: wrapper, original: fn }, false);
  }
  off(event, fn) {
    const list = this.#events.get(event);
    if (!list) return this;
    const index = list.findIndex((entry) => entry.original === fn || entry.fn === fn);
    if (index !== -1) list.splice(index, 1);
    if (list.length === 0) this.#events.delete(event);
    return this;
  }
  emit(event, ...args) {
    const list = this.#events.get(event);
    if (!list || list.length === 0) {
      if (event === 'error') throw args[0] instanceof Error ? args[0] : new Error('Unhandled error: ' + args[0]);
      return false;
    }
    for (const entry of [...list]) entry.fn.apply(this, args);       // a copy, so removal while emitting is safe
    return true;
  }
  listenerCount(event) { return this.#events.get(event)?.length ?? 0; }
}

const bus = new Emitter();
const seen = [];
const first = () => seen.push('first');
bus.on('go', first).once('go', function (x) { seen.push('once:' + x + ':' + (this === bus)); }).on('go', (x) => seen.push('last:' + x));
bus.prependListener('go', () => seen.push('prepended'));

console.log('emit returns      :', bus.emit('go', 1), bus.emit('nobody'));
bus.emit('go', 2);
console.log('calls             :', seen.join(' | '));
console.log('listeners now     :', bus.listenerCount('go'));

const removed = new Emitter();
const never = () => seen.push('never');
removed.once('x', never).off('x', never);
console.log('off before once   :', removed.emit('x'), 'listeners =', removed.listenerCount('x'));

const selfRemoving = new Emitter(); const order = [];
const a = () => { order.push('a'); selfRemoving.off('e', a); };
selfRemoving.on('e', a).on('e', () => order.push('b'));
selfRemoving.emit('e'); selfRemoving.emit('e');
console.log('self removal safe :', order.join(','));

try { new Emitter().emit('error', new Error('boom')); } catch (err) { console.log("'error' with no listener throws:", err.message); }

The same checks can be run against require('node:events') to compare the behaviour of the built-in class. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): emit returns : true false calls : prepended | first | once:1:true | last:1 | prepended | first | last:2 listeners now : 3 off before once : false listeners = 0 self removal safe : a,b,b 'error' with no listener throws: boom

Key points

  • Store listeners in arrays by event name.
  • emit is synchronous, in registration order, with this set to the emitter.
  • once removes itself before it runs, and off must also find it by the original function.
  • Copy the array before calling listeners.
  • Emitting 'error' with no listener should throw.

Common mistakes

  • Looping over the live array while listeners remove themselves.
  • Making off unable to remove a once listener.
  • Ignoring the special 'error' event.
  • Forgetting to remove listeners, which leaks memory.
  • Expecting emit to wait for async listeners.

Follow-ups

  • How does events.once(emitter, 'x') work?
  • What does setMaxListeners warn about?
  • How would you add async listeners in order (emitSerial)?

Tips

  • Describe the Map of arrays.
  • Call out the copy-before-loop detail.
  • Mention the 'error' event.
194.nodejs-0194Easyfresher

Implement a deep clone. How do you handle Date, Map, Set, circular references and functions, and why is structuredClone usually the better choice?

A deep clone copies nested objects recursively. Handle primitives, arrays, Date, RegExp, Map, Set and plain objects, and track already copied objects in a WeakMap so circular references do not recurse forever. JSON.parse(JSON.stringify(x)) loses Dates, undefined, Maps and Sets and fails on cycles. structuredClone handles most data types and cycles, but throws on functions and drops prototypes, so use it unless you need custom behaviour.

Full answer

Why not JSON

  • JSON.stringify turns Date into a string, drops undefined and functions, turns Map and Set into {}, turns NaN and Infinity into null, and throws on circular references and BigInt.

Writing it

  1. Return primitives (and functions, by reference) as they are.
  2. Keep a WeakMap from original to copy. If an object was seen already, return its copy. This handles cycles and also keeps shared references shared.
  3. Create the empty copy and register it in the WeakMap before copying children (important for cycles).
  4. Copy by type: Array (map the items), Date (new Date(value)), RegExp (keep source, flags, reset lastIndex), Map and Set (clone keys and values), plain objects (copy own enumerable string and symbol keys, keep the prototype with Object.create(Object.getPrototypeOf(x))).
  5. Decide about special cases: class instances with private fields cannot be copied by key copying, getters, non-enumerable properties and typed arrays.

structuredClone

  • Built in since Node 17. Handles cycles, Date, RegExp, Map, Set, ArrayBuffer, typed arrays and many errors. Throws DataCloneError on functions and some host objects, and class instances become plain objects (the prototype is lost).
  • For configuration and message data, prefer structuredClone. Write your own only for special needs.
javascript
function deepClone(value, seen = new WeakMap()) {
  if (value === null || typeof value !== 'object') return value;          // primitives and functions
  if (seen.has(value)) return seen.get(value);

  if (value instanceof Date) return new Date(value.getTime());
  if (value instanceof RegExp) return new RegExp(value.source, value.flags);

  if (value instanceof Map) {
    const copy = new Map(); seen.set(value, copy);
    for (const [k, v] of value) copy.set(deepClone(k, seen), deepClone(v, seen));
    return copy;
  }
  if (value instanceof Set) {
    const copy = new Set(); seen.set(value, copy);
    for (const v of value) copy.add(deepClone(v, seen));
    return copy;
  }
  if (Array.isArray(value)) {
    const copy = []; seen.set(value, copy);
    value.forEach((item, i) => { copy[i] = deepClone(item, seen); });
    return copy;
  }
  const copy = Object.create(Object.getPrototypeOf(value)); seen.set(value, copy);
  for (const key of Reflect.ownKeys(value)) {
    const descriptor = Object.getOwnPropertyDescriptor(value, key);
    if (descriptor.enumerable) copy[key] = deepClone(value[key], seen);
  }
  return copy;
}

const shared = { n: 1 };
const original = {
  date: new Date('2026-12-04T00:00:00Z'), pattern: /ab+c/gi, list: [1, [2, 3]], map: new Map([['k', { v: 1 }]]), set: new Set([1, 2]),
  missing: undefined, a: shared, b: shared, [Symbol.for('id')]: 7,
};
original.self = original;                                                // a circular reference

const copy = deepClone(original);
console.log('different objects      :', copy !== original, copy.list[1] !== original.list[1], copy.map.get('k') !== original.map.get('k'));
console.log('types kept             :', copy.date instanceof Date, copy.pattern.flags, copy.map instanceof Map, copy.set.has(2), 'missing' in copy);
console.log('cycle kept             :', copy.self === copy);
console.log('shared reference kept  :', copy.a === copy.b, '| symbol key copied:', copy[Symbol.for('id')]);

const json = (() => { try { return JSON.parse(JSON.stringify({ date: original.date, missing: undefined, map: original.map })); } catch (e) { return e.message; } })();
console.log('JSON round trip        :', JSON.stringify(json));
console.log('JSON with a cycle      :', (() => { try { JSON.stringify(original); } catch (e) { return e.name; } })());

const viaBuiltIn = structuredClone(original);
console.log('structuredClone cycle  :', viaBuiltIn.self === viaBuiltIn, '| Map kept:', viaBuiltIn.map instanceof Map);
console.log('structuredClone + fn   :', (() => { try { structuredClone({ f() {} }); } catch (e) { return e.name; } })());

A cyclic object with several types is cloned, then compared with a JSON round trip and with structuredClone. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): different objects : true true true types kept : true gi true true true cycle kept : true shared reference kept : true | symbol key copied: 7 JSON round trip : {"date":"2026-12-04T00:00:00.000Z","map":{}} JSON with a cycle : TypeError structuredClone cycle : true | Map kept: true structuredClone + fn : DataCloneError

Key points

  • JSON round trips lose many types and fail on cycles.
  • Use a WeakMap to handle cycles and shared references.
  • Register the copy before copying its children.
  • Handle Date, RegExp, Map, Set and arrays explicitly.
  • structuredClone is the built-in answer, except for functions and prototypes.

Common mistakes

  • Using JSON.parse(JSON.stringify(x)) for data that has dates, maps or cycles.
  • Recursing forever on circular references.
  • Copying the copy only after its children (the cycle then breaks).
  • Expecting structuredClone to copy functions or class prototypes.
  • Cloning big objects on a hot path.

Follow-ups

  • What does structuredClone do with a class instance?
  • How would you clone typed arrays and buffers?
  • When is a shallow copy with spread enough?

Tips

  • Start with the JSON problems.
  • Say 'WeakMap for cycles'.
  • Finish with structuredClone.
195.nodejs-0195Mediummid

Implement a simple HTTP router with path parameters, method matching, 404 and 405 responses, and middleware. How does it work?

A router keeps a list of routes (method, a compiled pattern and a handler). For a request it parses the path, finds the routes whose pattern matches, extracts named parameters, and calls the handler through a middleware chain with next(). If a path matches but the method does not, answer 405 with an Allow header, otherwise 404. Compile patterns once at registration, not per request.

Full answer

Registering routes

  • route('GET', '/students/:id', handler). Turn the path into a regular expression once: escape the literal parts and replace each :name with a named capture group, such as ([^/]+). Anchor the expression with ^ and $ and allow an optional trailing slash if you want that.
  • Store { method, regex, keys, handlers }.

Dispatching

  1. Parse the URL with new URL(req.url, 'http://x') to get pathname and query. Do not match against the raw URL with the query string.
  2. Loop through routes in order of registration. Collect routes whose pattern matches the path. If one also matches the method, use it. Decode parameters with decodeURIComponent (and handle a malformed value as a 400).
  3. If some routes matched the path but none the method, answer 405 and set the Allow header. If none matched, answer 404.
  4. HEAD can use GET handlers, and OPTIONS can answer from the Allow list.

Middleware

  • A middleware is (ctx, next). It does work, then calls next() to continue (await it for async code), or ends the response without calling next(). Compose the global middleware and the route handlers into one chain, and guard against calling next() twice.
  • Errors: wrap the chain in try/catch and send 500 without leaking details.

Design points: route order matters (a static /students/new should be registered before /students/:id), specificity scoring or a radix tree is faster than a linear scan, and production code should use a tested router (the one in Express, Fastify's find-my-way, or the URLPattern API in newer Node versions).

javascript
class Router {
  #routes = [];
  #middleware = [];

  use(fn) { this.#middleware.push(fn); return this; }
  route(method, path, ...handlers) {
    const keys = [];
    const source = path.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/:(\w+)/g, (_, name) => { keys.push(name); return '([^/]+)'; });
    this.#routes.push({ method, regex: new RegExp(`^${source}/?$`), keys, handlers });
    return this;
  }
  get(path, ...h) { return this.route('GET', path, ...h); }
  post(path, ...h) { return this.route('POST', path, ...h); }

  async handle(method, rawUrl) {
    const url = new URL(rawUrl, 'http://localhost');
    const ctx = { method, path: url.pathname, query: Object.fromEntries(url.searchParams), params: {}, status: 200, body: undefined, headers: {} };

    const matches = this.#routes.filter((r) => r.regex.test(ctx.path));
    const route = matches.find((r) => r.method === method);
    let final;
    if (route) {
      const values = route.regex.exec(ctx.path).slice(1);
      route.keys.forEach((key, i) => { ctx.params[key] = decodeURIComponent(values[i]); });
      final = route.handlers;
    } else if (matches.length) {
      final = [(c) => { c.status = 405; c.headers.Allow = matches.map((m) => m.method).join(', '); c.body = 'method not allowed'; }];
    } else {
      final = [(c) => { c.status = 404; c.body = 'not found'; }];
    }

    const chain = [...this.#middleware, ...final];
    let index = -1;
    const run = async (i) => {
      if (i <= index) throw new Error('next() called twice');
      index = i;
      if (chain[i]) await chain[i](ctx, () => run(i + 1));
    };
    try { await run(0); } catch (err) { ctx.status = 500; ctx.body = 'server error'; }
    return ctx;
  }
}

const app = new Router();
app.use(async (ctx, next) => { ctx.headers['x-before'] = '1'; await next(); ctx.headers['x-after'] = '1'; });
app.get('/students/new', (ctx) => { ctx.body = 'new form'; });
app.get('/students/:id', (ctx) => { ctx.body = { id: ctx.params.id, verbose: ctx.query.verbose === 'true' }; });
app.post('/students', (ctx) => { ctx.status = 201; ctx.body = 'created'; });
app.get('/boom', () => { throw new Error('secret detail'); });

(async () => {
  const show = async (method, url) => {
    const c = await app.handle(method, url);
    console.log(`${method} ${url}`.padEnd(32), c.status, JSON.stringify(c.body), c.headers.Allow ? 'Allow: ' + c.headers.Allow : '', c.headers['x-after'] ? '(middleware ran around it)' : '');
  };
  await show('GET', '/students/42?verbose=true');
  await show('GET', '/students/new');
  await show('GET', '/students/a%20b/');
  await show('POST', '/students');
  await show('DELETE', '/students');
  await show('GET', '/nothing');
  await show('GET', '/boom');
})();

The router is tested by calling handle(method, url) directly, so no HTTP server or port is needed. The same dispatch code could be called from an http.createServer callback. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): GET /students/42?verbose=true 200 {"id":"42","verbose":true} (middleware ran around it) GET /students/new 200 "new form" (middleware ran around it) GET /students/a%20b/ 200 {"id":"a b","verbose":false} (middleware ran around it) POST /students 201 "created" (middleware ran around it) DELETE /students 405 "method not allowed" Allow: POST (middleware ran around it) GET /nothing 404 "not found" (middleware ran around it) GET /boom 500 "server error"

Key points

  • Compile each path pattern into a regular expression once.
  • Match on pathname, not on the raw URL.
  • Return 405 with Allow when the path matches but the method does not.
  • Middleware is a chain of (ctx, next) functions.
  • Route order and specificity matter.

Common mistakes

  • Matching on req.url with the query string included.
  • Building a regular expression on every request.
  • Registering /:id before /new and shadowing it.
  • Answering 404 when the method is wrong (405 is correct).
  • Not decoding parameters or not handling bad encoding.

Follow-ups

  • How does a radix tree speed up routing?
  • What does the URLPattern API provide?
  • How do you handle a trailing slash and case sensitivity?

Tips

  • Describe register, match, run chain.
  • Mention 405 and Allow.
  • Say that you would use a library in production.
196.nodejs-0196Mediummid

Implement Promise.all, Promise.allSettled, Promise.race and Promise.any from scratch. What edge cases matter?

All four take an iterable, convert each item with Promise.resolve, and settle by different rules. all resolves with the values in input order and rejects at the first rejection. allSettled never rejects and reports status objects. race settles with the first settled promise. any resolves with the first fulfilled value and rejects with an AggregateError when all reject. Edge cases: an empty input, plain values in the input, and keeping the input order.

Full answer

Common steps

  1. Convert the iterable to an array (Array.from), because it may be a generator or a Set.
  2. Wrap each item with Promise.resolve(item) so plain values and thenables work.
  3. Attach handlers with then and keep the results by index, not by completion order.

Rules per method

  • all: count fulfilled items. When the count reaches the length, resolve with the array of values. On the first rejection, reject with that reason. An empty input resolves at once with [].
  • allSettled: for each item store { status: 'fulfilled', value } or { status: 'rejected', reason }. Resolve when every item has settled. It never rejects (empty input gives []).
  • race: attach resolve and reject of the new promise to every item. The first one to settle wins. An empty input never settles (the promise stays pending forever).
  • any: resolve with the first fulfilled value. Collect the rejection reasons by index. When all items have rejected, reject with an AggregateError that has the errors array. An empty input rejects at once with an AggregateError.

Details

  • Later settlements are ignored automatically, because a promise can settle once.
  • Do not use push in the then handler for all, because completion order breaks the result order. Assign results[index].
  • The other promises keep running after all or race settles. These methods do not cancel anything.
javascript
const all = (items) => new Promise((resolve, reject) => {
  const list = Array.from(items), results = new Array(list.length);
  let remaining = list.length;
  if (remaining === 0) return resolve([]);
  list.forEach((item, i) => Promise.resolve(item).then((value) => { results[i] = value; if (--remaining === 0) resolve(results); }, reject));
});

const allSettled = (items) => all(Array.from(items, (item) => Promise.resolve(item).then(
  (value) => ({ status: 'fulfilled', value }),
  (reason) => ({ status: 'rejected', reason }),
)));

const race = (items) => new Promise((resolve, reject) => {
  for (const item of items) Promise.resolve(item).then(resolve, reject);
});

const any = (items) => new Promise((resolve, reject) => {
  const list = Array.from(items), errors = new Array(list.length);
  let remaining = list.length;
  if (remaining === 0) return reject(new AggregateError([], 'All promises were rejected'));
  list.forEach((item, i) => Promise.resolve(item).then(resolve, (reason) => {
    errors[i] = reason;
    if (--remaining === 0) reject(new AggregateError(errors, 'All promises were rejected'));
  }));
});

const later = (ms, value) => new Promise((resolve) => setTimeout(resolve, ms, value));
const failLater = (ms, message) => new Promise((_, reject) => setTimeout(reject, ms, new Error(message)));

(async () => {
  console.log('all order kept      :', await all([later(30, 'slow'), 'plain', later(5, 'fast')]));
  console.log('all empty           :', await all([]));
  console.log('all rejects first   :', await all([later(30, 'x'), failLater(5, 'early')]).catch((e) => e.message));
  console.log('allSettled          :', JSON.stringify(await allSettled([later(5, 1), failLater(10, 'no'), 3]), (k, v) => (v instanceof Error ? v.message : v)));
  console.log('race first settled  :', await race([later(30, 'slow'), later(5, 'fast')]));
  console.log('race first rejection:', await race([later(30, 'slow'), failLater(5, 'quick failure')]).catch((e) => e.message));
  console.log('any first fulfilled :', await any([failLater(5, 'a'), later(20, 'good'), later(40, 'late')]));
  const err = await any([failLater(5, 'a'), failLater(10, 'b')]).catch((e) => e);
  console.log('any all rejected    :', err.constructor.name, err.errors.map((e) => e.message));
  console.log('matches built-ins   :', JSON.stringify(await all([1, later(5, 2)])) === JSON.stringify(await Promise.all([1, later(5, 2)])));
})();

The helper functions use short timers with gaps of at least 15 ms, so the order is stable. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): all order kept : [ 'slow', 'plain', 'fast' ] all empty : [] all rejects first : early allSettled : [{"status":"fulfilled","value":1},{"status":"rejected","reason":"no"},{"status":"fulfilled","value":3}] race first settled : fast race first rejection: quick failure any first fulfilled : good any all rejected : AggregateError [ 'a', 'b' ] matches built-ins : true

Key points

  • Convert input items with Promise.resolve and keep results by index.
  • all rejects on the first rejection; allSettled never rejects.
  • race follows the first settled promise; any follows the first fulfilled one.
  • Empty input: all and allSettled resolve, any rejects, race stays pending.
  • Nothing is cancelled.

Common mistakes

  • Pushing results in completion order in all.
  • Forgetting Promise.resolve for plain values.
  • Expecting race([]) to settle.
  • Thinking the losing promises are cancelled.
  • Confusing any with race.

Follow-ups

  • How would you add a concurrency limit to all?
  • What does AggregateError contain?
  • How do you cancel the work of losing promises?

Tips

  • Give one rule per method.
  • Mention index-based results.
  • Mention empty input.
197.nodejs-0197Hardsenior

Implement a minimal Promise class (then, catch, finally, resolve, reject) that follows the main rules of Promises/A+. How does asynchronous chaining work?

A promise has a state (pending, fulfilled, rejected), a value, and a list of handlers. It settles once. then registers handlers and returns a new promise, handlers always run asynchronously (queueMicrotask), and the value returned by a handler resolves the new promise through the resolution procedure: a promise or thenable is adopted, a plain value fulfils, a thrown error rejects, and resolving with the promise itself is a TypeError.

Full answer

State

  • state: pending, fulfilled or rejected. value: the result or the reason. handlers: callbacks waiting for settlement. Once settled, the state and value never change.

Constructor

  • Call executor(resolve, reject) in a try/catch. A throw rejects the promise. resolve and reject work only once (guard with a flag).

The resolution procedure resolve(x)

  • If x is the promise itself, reject with a TypeError (a chaining cycle).
  • If x is an object or function with a then method (a thenable, including real promises), call x.then with resolve and reject functions that again follow the procedure, and use the once-only guard. Errors while reading or calling then reject.
  • Otherwise fulfil with x.

then(onFulfilled, onRejected)

  • Returns a new promise. Store a handler record with the callbacks and the resolve and reject of the new promise. If the promise is already settled, schedule the handlers right away.
  • Handlers run asynchronously with queueMicrotask, even when the promise is already settled. If a callback is not a function, pass the value or reason through to the next promise.
  • The callback result goes to the new promise's resolve (through the procedure above). A throw in the callback rejects the new promise.

Helpers

  • catch(fn) is then(undefined, fn). finally(fn) runs fn and passes the original result or reason through, unless fn throws or returns a rejected promise.
  • Static resolve and reject create settled promises.

Real promises have extra features (species, internal slots, exact tick counts for await), so this is a teaching model. The official test suite promises-aplus-tests can check an implementation.

javascript
const PENDING = 0, FULFILLED = 1, REJECTED = 2;

class MyPromise {
  #state = PENDING;
  #value;
  #handlers = [];

  constructor(executor) {
    let called = false;
    const resolve = (x) => { if (!called) { called = true; this.#resolveWith(x); } };
    const reject = (reason) => { if (!called) { called = true; this.#settle(REJECTED, reason); } };
    try { executor(resolve, reject); } catch (err) { reject(err); }
  }

  #resolveWith(x) {
    if (x === this) return this.#settle(REJECTED, new TypeError('Chaining cycle detected'));
    if (x !== null && (typeof x === 'object' || typeof x === 'function')) {
      let then;
      try { then = x.then; } catch (err) { return this.#settle(REJECTED, err); }
      if (typeof then === 'function') {
        let called = false;
        try {
          then.call(x,
            (y) => { if (!called) { called = true; this.#resolveWith(y); } },
            (r) => { if (!called) { called = true; this.#settle(REJECTED, r); } });
        } catch (err) { if (!called) { called = true; this.#settle(REJECTED, err); } }
        return;
      }
    }
    this.#settle(FULFILLED, x);
  }

  #settle(state, value) {
    if (this.#state !== PENDING) return;
    this.#state = state; this.#value = value;
    this.#flush();
  }

  #flush() {
    if (this.#state === PENDING) return;
    const handlers = this.#handlers; this.#handlers = [];
    for (const handler of handlers) queueMicrotask(() => this.#run(handler));
  }

  #run({ onFulfilled, onRejected, resolve, reject }) {
    const callback = this.#state === FULFILLED ? onFulfilled : onRejected;
    if (typeof callback !== 'function') return (this.#state === FULFILLED ? resolve : reject)(this.#value);
    try { resolve(callback(this.#value)); } catch (err) { reject(err); }
  }

  then(onFulfilled, onRejected) {
    return new MyPromise((resolve, reject) => {
      this.#handlers.push({ onFulfilled, onRejected, resolve, reject });
      this.#flush();
    });
  }
  catch(onRejected) { return this.then(undefined, onRejected); }
  finally(fn) {
    return this.then(
      (value) => MyPromise.resolve(fn()).then(() => value),
      (reason) => MyPromise.resolve(fn()).then(() => { throw reason; }));
  }
  static resolve(x) { return x instanceof MyPromise ? x : new MyPromise((resolve) => resolve(x)); }
  static reject(reason) { return new MyPromise((_, reject) => reject(reason)); }
}

(async () => {
  // 1. Handlers run asynchronously, and interleave with native promises one step at a time.
  const log = [];
  Promise.resolve().then(() => log.push('native 1')).then(() => log.push('native 2'));
  MyPromise.resolve().then(() => log.push('mine 1')).then(() => log.push('mine 2'));
  log.push('sync');
  await new Promise((r) => setTimeout(r, 10));
  console.log('1.', log.join(', '));

  // 2. Chaining: values, thrown errors, thenables and native promises are all adopted.
  const chained = await MyPromise.resolve(1).then((n) => n + 1).then((n) => Promise.resolve(n * 10)).then((n) => ({ then: (ok) => ok(n + 5) }));
  console.log('2. chained value:', chained);
  console.log('3. error path   :', await MyPromise.resolve().then(() => { throw new Error('bad'); }).catch((e) => 'caught ' + e.message).finally(() => {}));

  // 4. Settles once; executor throw rejects; cycle is a TypeError.
  console.log('4. settle once  :', await new MyPromise((resolve, reject) => { resolve('first'); resolve('second'); reject(new Error('ignored')); }));
  console.log('   executor throw:', await new MyPromise(() => { throw new Error('in executor'); }).catch((e) => e.message));
  const cyclic = MyPromise.resolve().then(() => cyclic);
  console.log('   cycle         :', await cyclic.catch((e) => e.constructor.name));

  // 5. await works on it, because it has a then method.
  console.log('5. awaited      :', await new MyPromise((resolve) => setTimeout(resolve, 5, 'done')));
  console.log('6. finally passes the value on:', await MyPromise.resolve('kept').finally(() => 'ignored'));
})();

A teaching model, not a replacement for the built-in Promise. It was checked with the cases in the script only, not with the promises-aplus-tests suite. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): 1. sync, native 1, mine 1, native 2, mine 2 2. chained value: 25 3. error path : caught bad 4. settle once : first executor throw: in executor cycle : TypeError 5. awaited : done 6. finally passes the value on: kept

Key points

  • Settle once; keep state and value.
  • then returns a new promise and always runs handlers asynchronously.
  • The resolution procedure adopts thenables.
  • A throw in a handler rejects the next promise.
  • catch and finally are built on then.

Common mistakes

  • Running handlers synchronously when the promise is already settled.
  • Not guarding resolve and reject against being called twice.
  • Forgetting to adopt thenables, so promises are not flattened.
  • Letting the same promise be resolved with itself.
  • Calling handlers of one then in the wrong order.

Follow-ups

  • Why must then handlers run asynchronously?
  • How does await use the then method?
  • What are unhandled rejections in this model?

Tips

  • Describe the state machine first.
  • Explain the resolution procedure.
  • Say that this is for learning.
198.nodejs-0198Easyfresher

Implement small utilities from scratch: flatten, chunk, groupBy, uniqueBy and memoize. What are the edge cases?

These five helpers cover most utility questions. flatten recurses (or uses a stack) with a depth limit, chunk slices an array in fixed sizes and rejects a size below one, groupBy builds an object (or Map) of arrays by a key function, uniqueBy keeps the first item per key with a Set, and memoize caches results by an argument key. Edge cases: empty input, nested empties, key collisions, and memory growth in a cache.

Full answer
  • flatten(array, depth): for each item, if it is an array and depth remains, flatten it with depth - 1, else push it. Array.prototype.flat does the same, so the exercise is about recursion and the depth rule (Infinity means all levels). Very deep arrays can exceed the call stack with recursion, which an explicit stack avoids.
  • chunk(array, size): loop with index += size and slice. Reject size less than 1 (an infinite loop otherwise). The last chunk can be shorter. An empty array gives [].
  • groupBy(array, keyFn): use a loop and an object or Map, pushing each item to its group. Use Object.create(null) or a Map when keys can be user input, to avoid keys such as proto causing trouble. Node 21 and later also has Object.groupBy and Map.groupBy.
  • uniqueBy(array, keyFn): a Set of seen keys, keep the first item per key and keep the order. For primitives, [...new Set(array)] is enough.
  • memoize(fn, keyFn): a Map from key to result. The default key must be chosen carefully (JSON.stringify of arguments is simple but slow and wrong for functions and cycles). Cache promises, not only values, for async functions, so that concurrent calls share work. Limit the size (LRU) or the cache grows without bound, which is a memory leak for functions with many different inputs.

Interview habits: ask about edge cases first, state the time and space complexity (all of these are O(n) except flatten with deep nesting), and write a few small tests.

javascript
const flatten = (array, depth = Infinity) =>
  array.reduce((out, item) => (Array.isArray(item) && depth > 0 ? out.concat(flatten(item, depth - 1)) : (out.push(item), out)), []);

function chunk(array, size) {
  if (!Number.isInteger(size) || size < 1) throw new RangeError('size must be a positive integer');
  const out = [];
  for (let i = 0; i < array.length; i += size) out.push(array.slice(i, i + size));
  return out;
}

function groupBy(array, keyFn) {
  const groups = Object.create(null);
  for (const item of array) (groups[keyFn(item)] ??= []).push(item);
  return groups;
}

function uniqueBy(array, keyFn) {
  const seen = new Set();
  return array.filter((item) => { const key = keyFn(item); if (seen.has(key)) return false; seen.add(key); return true; });
}

function memoize(fn, keyFn = (...args) => JSON.stringify(args)) {
  const cache = new Map();
  const memoized = (...args) => {
    const key = keyFn(...args);
    if (cache.has(key)) return cache.get(key);
    const result = fn(...args);
    cache.set(key, result);                      // for async functions this stores the promise, so concurrent calls share it
    return result;
  };
  memoized.cache = cache;
  return memoized;
}

console.log('flatten all   :', JSON.stringify(flatten([1, [2, [3, [4, []]]], 5])));
console.log('flatten depth1:', JSON.stringify(flatten([1, [2, [3, [4]]]], 1)), '| same as flat(1):', JSON.stringify([1, [2, [3, [4]]]].flat(1)) === JSON.stringify(flatten([1, [2, [3, [4]]]], 1)));
console.log('chunk         :', JSON.stringify(chunk([1, 2, 3, 4, 5], 2)), JSON.stringify(chunk([], 3)));
console.log('chunk size 0  :', (() => { try { chunk([1], 0); } catch (e) { return e.name; } })());

const people = [{ name: 'Asha', city: 'Pune' }, { name: 'Ravi', city: 'Delhi' }, { name: 'Meera', city: 'Pune' }, { name: 'Asha', city: 'Goa' }];
console.log('groupBy city  :', JSON.stringify(groupBy(people, (p) => p.city)));
console.log('groupBy __proto__ safe:', JSON.stringify(groupBy([{ k: '__proto__' }], (x) => x.k)), '| Object.groupBy equal:', JSON.stringify(groupBy(people, (p) => p.city)) === JSON.stringify(Object.groupBy(people, (p) => p.city)));
console.log('uniqueBy name :', uniqueBy(people, (p) => p.name).map((p) => p.city).join(', '));

let calls = 0;
const square = memoize((n) => { calls++; return n * n; });
square(4); square(4); square(5);
console.log('memoize       : calls =', calls, '| cache size =', square.cache.size);

The utilities are checked with small inputs and, where a built-in exists (flat, Object.groupBy), against the built-in result. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): flatten all : [1,2,3,4,5] flatten depth1: [1,2,[3,[4]]] | same as flat(1): true chunk : [[1,2],[3,4],[5]] [] chunk size 0 : RangeError groupBy city : {"Pune":[{"name":"Asha","city":"Pune"},{"name":"Meera","city":"Pune"}],"Delhi":[{"name":"Ravi","city":"Delhi"}],"Goa":[{"name":"Asha","city":"Goa"}]} groupBy __proto__ safe: {"__proto__":[{"k":"__proto__"}]} | Object.groupBy equal: true uniqueBy name : Pune, Delhi, Pune memoize : calls = 2 | cache size = 2

Key points

  • flatten needs a depth rule and a recursion or stack choice.
  • chunk must reject sizes below one.
  • groupBy should be safe against odd keys such as __proto__.
  • uniqueBy keeps the first item and the order.
  • memoize needs a good key and a size limit.

Common mistakes

  • Using a plain object for groups, so '__proto__' or 'constructor' keys misbehave.
  • An infinite loop in chunk when size is 0.
  • Memoizing with a key that collides (for example arguments joined with a comma).
  • A cache with no size limit.
  • Mutating the input array.

Follow-ups

  • How would you add an LRU limit to memoize?
  • What is the complexity of each function?
  • How does Map.groupBy differ from Object.groupBy?

Tips

  • Ask about edge cases first.
  • State complexity.
  • Say when the built-in exists.
199.nodejs-0199Hardsenior

Implement a circuit breaker for calls to an unreliable service. What are its states, and what settings matter?

A circuit breaker stops calling a failing dependency so that it can recover and so that callers fail fast. It has three states. Closed: calls go through and failures are counted. Open: calls fail at once for a cool-down period. Half-open: after the cool-down, a limited number of trial calls are allowed, and one success closes the breaker while a failure opens it again. Combine it with timeouts, retries with backoff, and fallbacks.

Full answer

States

  • Closed (normal): calls pass through. Track failures. When consecutive failures reach a threshold (or the failure rate in a window crosses a limit), switch to open and record the time.
  • Open: do not call the dependency. Reject at once with a clear error (fail fast), or use a fallback (cached data, a default). This protects the failing service from extra load and protects your own resources (threads, sockets, queue length).
  • Half-open: when the reset timeout has passed, allow one trial call (or a few). On success, go back to closed and reset the counters. On failure, go back to open and restart the timer. Only the allowed number of trial calls may pass while others are rejected.

Settings

  • failureThreshold (or error percentage and minimum number of calls in a window), resetTimeout, call timeout, and which errors count as failures (a 400 caused by a bad request is not a dependency failure, a timeout or a 503 is).
  • Per dependency, not one global breaker.

Details and pairing

  • Always put a timeout on the wrapped call. A slow dependency is the main reason for breakers.
  • Retries belong inside or outside of the breaker by design, but they must not multiply the load on a failing service. Use backoff with jitter.
  • Expose state and counters as metrics and logs, and alert when a breaker opens.
  • In a cluster each process has its own breaker unless the state is shared. That is usually fine.
  • Libraries: opossum is a well-known Node implementation.
javascript
class CircuitBreaker {
  #state = 'closed'; #failures = 0; #openedAt = 0; #trialInFlight = false;
  constructor(fn, { failureThreshold = 3, resetTimeout = 1000, now = Date.now } = {}) {
    this.fn = fn; this.failureThreshold = failureThreshold; this.resetTimeout = resetTimeout; this.now = now;
  }
  get state() { return this.#state; }

  async call(...args) {
    if (this.#state === 'open') {
      if (this.now() - this.#openedAt < this.resetTimeout) throw new Error('circuit open');
      this.#state = 'half-open';
    }
    if (this.#state === 'half-open') {
      if (this.#trialInFlight) throw new Error('circuit half-open, trial in progress');
      this.#trialInFlight = true;
    }
    try {
      const result = await this.fn(...args);
      this.#failures = 0; this.#state = 'closed';
      return result;
    } catch (err) {
      this.#failures++;
      if (this.#state === 'half-open' || this.#failures >= this.failureThreshold) { this.#state = 'open'; this.#openedAt = this.now(); }
      throw err;
    } finally {
      this.#trialInFlight = false;
    }
  }
}

(async () => {
  let clock = 0, healthy = false, upstreamCalls = 0;
  const service = async () => { upstreamCalls++; if (!healthy) throw new Error('503 from service'); return 'ok'; };
  const breaker = new CircuitBreaker(service, { failureThreshold: 3, resetTimeout: 1000, now: () => clock });
  const attempt = async (label) => {
    const result = await breaker.call().catch((e) => e.message);
    console.log(label.padEnd(30), 'state =', breaker.state.padEnd(9), '|', result, '| upstream calls so far:', upstreamCalls);
  };

  for (let i = 1; i <= 3; i++) await attempt(`failure ${i}`);
  await attempt('call while open');
  await attempt('call while open (again)');

  clock += 1000;                                   // the cool-down has passed
  await attempt('trial fails (still broken)');
  await attempt('call right after reopening');

  clock += 1000; healthy = true;
  await attempt('trial succeeds');
  await attempt('normal call');
})();

The clock is injected, so the cool-down is simulated by changing a number. Concurrent calls were not tested in this script. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): failure 1 state = closed | 503 from service | upstream calls so far: 1 failure 2 state = closed | 503 from service | upstream calls so far: 2 failure 3 state = open | 503 from service | upstream calls so far: 3 call while open state = open | circuit open | upstream calls so far: 3 call while open (again) state = open | circuit open | upstream calls so far: 3 trial fails (still broken) state = open | 503 from service | upstream calls so far: 4 call right after reopening state = open | circuit open | upstream calls so far: 4 trial succeeds state = closed | ok | upstream calls so far: 5 normal call state = closed | ok | upstream calls so far: 6

Key points

  • Closed counts failures, open fails fast, half-open tests recovery.
  • Only the allowed trial calls pass in half-open.
  • Choose which errors count as failures.
  • Use one breaker per dependency, with timeouts and metrics.
  • Combine with retries and fallbacks, carefully.

Common mistakes

  • Opening the breaker for client errors such as 400 or 404.
  • No timeout, so slow calls never count as failures.
  • Letting every request through in half-open state.
  • One global breaker for many unrelated dependencies.
  • Retrying aggressively behind an open breaker.

Follow-ups

  • How does a failure rate window differ from a consecutive failure count?
  • What fallback would you use for a read endpoint?
  • How do bulkheads relate to circuit breakers?

Tips

  • Draw the three states.
  • Mention timeouts and what counts as failure.
  • Say that the library opossum exists.
200.nodejs-0200Hardsenior

How would you design a reliable webhook delivery system in Node.js, covering signing, retries, idempotency, ordering and what the receiver must do?

Write events to a durable store, deliver them from a queue with workers, sign each request (HMAC over a timestamp and the body), and retry with exponential backoff and jitter until a limit, then park them in a dead letter list. Delivery is at least once, so every event has an id that the receiver uses to deduplicate. Receivers verify the signature with a constant-time comparison, check the timestamp, answer quickly with 2xx and process in the background.

Full answer

Sender side

  1. Durable first: save the event (id, type, payload, endpoint, status) in the database in the same transaction as the business change (the outbox pattern). A separate worker reads the outbox and enqueues delivery jobs (BullMQ, SQS). This avoids losing events when the process crashes.
  2. Delivery worker: POST with a short timeout (5 to 10 seconds), headers for event id, timestamp and signature. Success means a 2xx status. Treat 5xx, 429 and network errors as retryable. 4xx (except 408 and 429) is usually permanent, but many senders retry a few times anyway.
  3. Retries: exponential backoff with jitter (for example 1 minute, 5 minutes, 30 minutes, 2 hours, up to a day or more). After the maximum attempts, move to a dead letter state, alert the customer, and offer manual replay. Disable endpoints that fail for days.
  4. Security: sign with HMAC-SHA256 using a per-endpoint secret over timestamp + '.' + raw body. Allow secret rotation (two valid secrets). Block requests to private IP ranges to prevent SSRF, use HTTPS only, and do not follow redirects blindly.
  5. Fairness: one slow customer must not block others. Use a queue per endpoint or per customer, concurrency limits and rate limits.
  6. Ordering: at-least-once delivery with retries does not keep order. Give each event a sequence number or timestamp and tell receivers to treat events as hints, or fetch the current resource state from your API.
  7. Observability: a delivery log with attempts, status codes and latency, and a replay button.

Receiver side

  • Read the raw body (before JSON parsing), verify the signature with crypto.timingSafeEqual, reject old timestamps (for example older than 5 minutes) to stop replays, answer 2xx fast, enqueue the work, and deduplicate by event id (a unique key in the database).
javascript
const crypto = require('node:crypto');

const sign = (secret, timestamp, body) => crypto.createHmac('sha256', secret).update(`${timestamp}.${body}`).digest('hex');

function verify({ secret, header, body, now, toleranceSeconds = 300 }) {
  const [t, v1] = header.split(',').map((part) => part.split('=')[1]);
  if (Math.abs(now - Number(t)) > toleranceSeconds) return 'rejected: timestamp too old';
  const expected = Buffer.from(sign(secret, t, body), 'hex');
  const received = Buffer.from(v1, 'hex');
  return expected.length === received.length && crypto.timingSafeEqual(expected, received) ? 'accepted' : 'rejected: bad signature';
}

// Backoff with full jitter. The random function is injected, so the output is stable.
const delaySeconds = (attempt, random = Math.random, base = 60, cap = 6 * 3600) => Math.floor(random() * Math.min(cap, base * 2 ** (attempt - 1)));

const secret = 'whsec_demo_secret';
const event = { id: 'evt_1001', type: 'course.completed', data: { student: 'Asha' } };
const body = JSON.stringify(event);
const t = 1_800_000_000;
const header = `t=${t},v1=${sign(secret, t, body)}`;

console.log('valid delivery        :', verify({ secret, header, body, now: t + 5 }));
console.log('tampered body         :', verify({ secret, header, body: body.replace('Asha', 'Ravi'), now: t + 5 }));
console.log('wrong secret          :', verify({ secret: 'other', header, body, now: t + 5 }));
console.log('replay after 10 min   :', verify({ secret, header, body, now: t + 600 }));
console.log('max backoff per attempt (seconds):', [1, 2, 3, 4, 5, 6, 7, 8].map((n) => delaySeconds(n, () => 0.999999)).join(', '));
console.log('with random = 0.5     :', [1, 2, 3, 4, 5].map((n) => delaySeconds(n, () => 0.5)).join(', '));

// The receiver deduplicates by event id.
const processed = new Set();
const receive = (evt) => (processed.has(evt.id) ? 'duplicate ignored' : (processed.add(evt.id), 'processed'));
console.log('same event delivered twice:', receive(event), '|', receive(event));

The signing, verification, replay window and backoff numbers are run here. The queue, the outbox table and the network delivery are described in the text and were not built or run. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): valid delivery : accepted tampered body : rejected: bad signature wrong secret : rejected: bad signature replay after 10 min : rejected: timestamp too old max backoff per attempt (seconds): 59, 119, 239, 479, 959, 1919, 3839, 7679 with random = 0.5 : 30, 60, 120, 240, 480 same event delivered twice: processed | duplicate ignored

Key points

  • Store events durably (outbox) and deliver from a queue.
  • Sign timestamp plus raw body with HMAC and compare in constant time.
  • Retry with backoff and jitter, then dead letter and replay.
  • Delivery is at least once and unordered, so receivers must deduplicate.
  • Isolate customers and protect against SSRF.

Common mistakes

  • Verifying the signature over parsed JSON instead of the raw body.
  • Comparing signatures with === (timing leak).
  • Doing slow work before answering 2xx, so the sender retries.
  • Retrying immediately and flooding a failing endpoint.
  • Assuming events arrive once and in order.

Follow-ups

  • How would you rotate a signing secret without downtime?
  • How do you prevent SSRF in a webhook sender?
  • What would a replay endpoint need to be safe?

Tips

  • Cover sender and receiver separately.
  • Say 'at least once, so deduplicate'.
  • Mention outbox, signing, backoff and dead letters.