Questions 101–120 of 200 · 0 of 20 on this page marked learned
101.nodejs-0101Mediummid
A stream pipeline never finishes and the process exits quietly. How do you find out why a stream has stalled?
A stream stalls when one stage never calls its callback, nobody consumes the readable side, or the writer ignores 'drain'. Node does not warn, and when no timer or socket is left the process simply exits, often with code 0. Inspect readableFlowing, readableLength, writableLength and writableNeedDrain on each stage to see where data stopped, and add a watchdog timer in tests.
Full answer
Stalled streams are hard to see because nothing throws. A stream is a state machine, so the way to debug it is to read its state.
The usual causes:
A Transform or Writable never calls its callback for a chunk (a missed code path, an early return). The next chunk is never requested.
A Readable has no consumer. Until you attach a 'data' listener, call resume(), pipe it or iterate it, nothing flows (readableFlowing is null).
A writer loop ignores the false result of write() and never waits for 'drain', or waits for 'drain' that was never needed.
One side finished but the other side was never ended (end() was not called, or push(null) was missing).
An error is swallowed because pipe() was used without handlers.
Useful properties:
readable.readableFlowing: null (nobody has asked yet), true or false (paused).
readable.readableLength and writable.writableLength: bytes or objects waiting in the buffer.
writable.writableNeedDrain: true when write() returned false and 'drain' has not fired yet.
readable.readableEnded and writable.writableFinished: the end of each side was reached.
Process exit is a clue. If the event loop has nothing left to do, Node exits. A pipeline that is waiting for a callback that will never come does not keep the process alive, so you see no error and no output. In a service this shows up as requests that hang while the stream sits idle with open sockets.
Habits that prevent it: use stream/promises pipeline, put timeouts on network streams, call the callback in every code path (use try/finally), and test streams with a short watchdog timer.
javascript
const { Readable, Transform, Writable, pipeline } = require('node:stream');
// Bug: the transform never calls its callback for the chunk 'b'.
const buggy = new Transform({
transform(chunk, encoding, callback) {
if (chunk.toString() === 'b') return; // forgot callback()
callback(null, chunk);
},
});
const sink = new Writable({ write(chunk, enc, cb) { console.log('sink got', chunk.toString()); cb(); } });
let finished = false;
pipeline(Readable.from(['a', 'b', 'c']), buggy, sink, () => { finished = true; });
// A watchdog turns the silent stall into a report.
setTimeout(() => {
console.log('after 50 ms: pipeline finished =', finished);
console.log('transform writableLength:', buggy.writableLength, '| writableNeedDrain:', buggy.writableNeedDrain);
console.log('transform readableLength:', buggy.readableLength, '| sink writableFinished:', sink.writableFinished);
// A Readable with no consumer does not flow.
const idle = Readable.from(['x', 'y']);
console.log('no consumer: readableFlowing =', idle.readableFlowing);
idle.resume();
console.log('after resume(): readableFlowing =', idle.readableFlowing);
// Ignoring the result of write().
const slow = new Writable({ highWaterMark: 4, write(chunk, enc, cb) { setTimeout(cb, 5); } });
const accepted = slow.write('12345678');
console.log('write() returned', accepted, '| writableNeedDrain =', slow.writableNeedDrain);
slow.once('drain', () => { console.log('drain fired, safe to write again'); process.exit(0); });
}, 50);
The first part stalls because one callback is missing. The watchdog timer keeps the process alive long enough to print the state of each stage. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
sink got a
after 50 ms: pipeline finished = false
transform writableLength: 2 | writableNeedDrain: false
transform readableLength: 0 | sink writableFinished: false
no consumer: readableFlowing = null
after resume(): readableFlowing = true
write() returned false | writableNeedDrain = true
drain fired, safe to write again
Key points
Stalls produce no error, so read the stream state.
Missing callbacks, no consumer and ignored drain are the usual causes.
readableFlowing, readableLength, writableNeedDrain show where data stopped.
A stalled pipeline may let the process exit with code 0.
Common mistakes
Using pipe() without error handlers and wondering why nothing is logged.
Returning early from transform() without calling the callback.
Calling write() in a loop without checking its return value.
Adding a 'readable' listener and a 'data' listener together and expecting both to flow.
Forgetting that a hung network stream needs a timeout.
Follow-ups
What does the process exit code tell you when a top-level await never settles?
How does stream.finished help detect a stream that ended or failed?
How would you add a stall timeout to a streaming HTTP download?
Tips
Name the three usual causes first.
Mention the stream state properties by name.
Say that Node exits silently when nothing keeps the loop alive.
102.nodejs-0102Mediummid
How do errors, abort signals and early closes behave in stream.pipeline, and what is ERR_STREAM_PREMATURE_CLOSE?
stream/promises pipeline rejects with the first error and destroys every stream. An AbortSignal rejects with AbortError and destroys the streams. If a stream closes before it has ended normally, for example a client disconnects, the error is ERR_STREAM_PREMATURE_CLOSE. An async generator stage can transform data, and an exception inside it fails the pipeline like any other error.
Full answer
pipeline from node:stream/promises returns a promise. It settles when the last stream finishes or when anything goes wrong, and in both cases it cleans up.
Cases to know:
Error in any stage: the promise rejects with that error, and all other streams are destroyed.
AbortSignal: pass { signal } as the last argument. When the signal aborts, the promise rejects with an AbortError and the streams are destroyed. This is how you add a timeout or tie a stream to a request.
Premature close: a stream that closes before it finished writing or reading normally produces ERR_STREAM_PREMATURE_CLOSE. For example, a destination socket that the client closed. It is usually a normal event for downloads, so log it at a low level.
Async generator stages: a function* async stage reads the previous stage with for await and yields chunks. It is shorter than a Transform. Throwing inside it rejects the pipeline.
stream.finished(stream) resolves when the stream is done and rejects when it errored or closed early. It is the tool for one stream when you do not use pipeline.
Rules that avoid leaks:
Prefer pipeline over pipe. pipe does not destroy the other streams on error.
Always handle the rejection. An unhandled pipeline rejection becomes an unhandled promise rejection.
Do not call destroy() on a stream and then wait for 'end'. A destroyed stream emits 'close', not 'end'.
For HTTP servers, pass the request or response in the pipeline so a closed connection stops the work.
javascript
const { pipeline, finished } = require('node:stream/promises');
const { Readable, Writable } = require('node:stream');
const endless = () => new Readable({ read() { setTimeout(() => this.push('x'), 5); } });
const sink = () => new Writable({ write(chunk, enc, cb) { cb(); } });
async function main() {
// 1. Abort after 30 ms.
const controller = new AbortController();
const source1 = endless();
const sink1 = sink();
setTimeout(() => controller.abort(), 30);
await pipeline(source1, sink1, { signal: controller.signal })
.catch((err) => console.log('1. abort ->', err.name, '| source destroyed:', source1.destroyed, '| sink destroyed:', sink1.destroyed));
// 2. The destination closes before the pipeline is done.
const source2 = endless();
const early = new Writable({ write(chunk, enc, cb) { cb(); this.destroy(); } });
await pipeline(source2, early)
.catch((err) => console.log('2. early close ->', err.code, '| source destroyed:', source2.destroyed));
// 3. An async generator stage throws.
await pipeline(
Readable.from([1, 2, 3]),
async function* (source) {
for await (const n of source) {
if (n === 2) throw new Error('bad item ' + n);
yield String(n);
}
},
sink(),
).catch((err) => console.log('3. generator stage ->', err.message));
// 4. finished() on a stream that was destroyed without ending.
const manual = new Readable({ read() {} });
const watch = finished(manual).catch((err) => console.log('4. finished ->', err.code));
manual.destroy();
await watch;
// 5. Success path, for comparison.
const chunks = [];
await pipeline(Readable.from(['a', 'b']), new Writable({ write(c, e, cb) { chunks.push(c.toString()); cb(); } }));
console.log('5. success -> wrote', chunks.join(''));
}
main();
Each case ends with the stream error code or name. In every failing case the other streams are destroyed. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
1. abort -> AbortError | source destroyed: true | sink destroyed: true
2. early close -> ERR_STREAM_PREMATURE_CLOSE | source destroyed: true
3. generator stage -> bad item 2
4. finished -> ERR_STREAM_PREMATURE_CLOSE
5. success -> wrote ab
Key points
pipeline rejects with the first error and destroys all streams.
{ signal } turns an abort into an AbortError and cleans up.
A stream that closes too early gives ERR_STREAM_PREMATURE_CLOSE.
Async generator stages are the short way to write a transform.
finished() watches one stream for end, error or early close.
Common mistakes
Using pipe() and leaving the source open after the destination failed.
Not catching the pipeline promise.
Treating ERR_STREAM_PREMATURE_CLOSE on a download as a server bug.
Waiting for 'end' on a stream that was destroyed.
Passing the signal in the wrong position: it belongs in the options object at the end.
Follow-ups
How do you stop work when an HTTP client disconnects?
What is the difference between destroy() and end()?
How does stream.compose differ from pipeline?
Tips
Give the three outcomes: error, abort, premature close.
Show the async generator stage because it is short.
Mention that a download client closing is normal.
103.nodejs-0103Easyfresher
What is object mode in Node.js streams, and how do Readable.from and generators help you create object streams?
Normal streams carry strings and Buffers. In object mode a stream carries any JavaScript value except null, and highWaterMark counts objects (16 by default) instead of bytes. Readable.from(iterable) creates an object-mode readable from an array, a generator or an async generator. Use object mode for rows, events and parsed records.
Full answer
By default a stream moves bytes. Writing a plain object to a normal Writable throws ERR_INVALID_ARG_TYPE. Object mode removes that limit.
Facts to remember:
Set objectMode: true on a Readable, Writable, Transform or Duplex. A Transform can use readableObjectMode and writableObjectMode separately, for example bytes in and objects out (a parser) or objects in and bytes out (a serializer).
highWaterMark is a count of objects, default 16, instead of 64 KB of bytes. Backpressure still works, but it counts items, not sizes. A few huge objects can still use a lot of memory.
null is the end marker, so it cannot be pushed as data. undefined is allowed in some cases but should be avoided.
Readable.from(iterable) is the easiest source. Arrays, sync generators and async generators work. By default the result is in object mode. A string passed directly is one chunk, not one character per chunk.
Async iteration with for await...of is the simplest consumer.
Typical uses: database rows, parsed CSV or JSON lines, events from a message queue, and any stage where a record is the unit of work.
Costs: each object passes through the stream machinery, so object streams are slower per byte than byte streams. For hot paths, batch records into arrays (for example 500 rows at a time).
javascript
const { Readable, Writable, Transform } = require('node:stream');
console.log('byte stream highWaterMark:', new Readable().readableHighWaterMark);
console.log('object mode highWaterMark:', new Readable({ objectMode: true }).readableHighWaterMark);
// A normal Writable refuses objects.
const bytesOnly = new Writable({ write(chunk, enc, cb) { cb(); } });
bytesOnly.on('error', () => {});
try { bytesOnly.write({ id: 1 }); } catch (err) { console.log('object into byte stream ->', err.code); }
// Readable.from accepts arrays and generators and uses object mode.
function* students() {
yield { name: 'Asha', marks: 78 };
yield { name: 'Ravi', marks: 64 };
yield { name: 'Meera', marks: 91 };
}
const source = Readable.from(students());
console.log('Readable.from objectMode:', source.readableObjectMode);
// Bytes in, objects out: a tiny parser for lines like "name,marks".
const parse = new Transform({
readableObjectMode: true,
transform(chunk, enc, cb) {
for (const line of chunk.toString().split('\n').filter(Boolean)) {
const [name, marks] = line.split(',');
this.push({ name, marks: Number(marks) });
}
cb();
},
});
async function main() {
const best = [];
for await (const row of source) if (row.marks > 70) best.push(row.name);
console.log('marks above 70:', best.join(', '));
parse.end('Asha,78\nRavi,64\n');
const rows = [];
for await (const row of parse) rows.push(row);
console.log('parsed rows:', JSON.stringify(rows));
// A string is one chunk, not one chunk per character.
let count = 0;
for await (const piece of Readable.from('hello')) count++;
console.log('chunks from Readable.from("hello"):', count);
}
main();
Readable.from is used with a generator, and a Transform turns text lines into objects. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
byte stream highWaterMark: 65536
object mode highWaterMark: 16
object into byte stream -> ERR_INVALID_ARG_TYPE
Readable.from objectMode: true
marks above 70: Asha, Meera
parsed rows: [{"name":"Asha","marks":78},{"name":"Ravi","marks":64}]
chunks from Readable.from("hello"): 1
Key points
Object mode streams carry any value except null.
highWaterMark counts objects (default 16), not bytes.
Transform can mix byte input and object output.
Readable.from(iterable) creates an object-mode readable.
Batch records when per-object overhead matters.
Common mistakes
Pushing null to mean 'no value'. It ends the stream.
Assuming highWaterMark is in bytes in object mode.
Forgetting objectMode on one side of a Transform that needs it.
Using object mode for large binary data.
Expecting Readable.from('text') to emit characters.
Follow-ups
How does backpressure work when objects have very different sizes?
How do you batch objects before writing them to a database?
What is the difference between readableObjectMode and writableObjectMode?
Tips
Say that highWaterMark counts items.
Show Readable.from with a generator.
Mention batching for speed.
104.nodejs-0104Mediummid
How do you write a custom Transform stream, and why must it handle partial chunks and implement flush?
Extend Transform (or pass a transform function), call this.push for each output item and call the callback when the chunk is handled. Chunks do not respect message boundaries, so keep the incomplete tail in a buffer between calls. Implement flush to emit whatever is left at the end, or the last line is lost.
Full answer
A Transform has a writable side (input) and a readable side (output). You provide two methods:
transform(chunk, encoding, callback): called for each input chunk. Call this.push(output) zero or more times, then callback(). callback(err) fails the stream. callback(null, data) is a shortcut for one push.
flush(callback): called once after the last chunk and before 'end'. Emit leftovers here.
Why partial chunks matter: a file stream or a socket splits data at arbitrary byte positions, not at line ends. One line can arrive in two chunks, and one chunk can hold several lines. A line splitter therefore keeps a string buffer of the unfinished tail.
Details that cause bugs:
Multi-byte characters can be cut by a chunk boundary. Use StringDecoder (or set decodeStrings and encoding correctly) so you do not decode half a character.
Always call the callback exactly once for each transform call, and also on error paths.
Use readableObjectMode: true when the output is lines or objects and not Buffers.
Respect backpressure: push returns false when the readable buffer is full. Inside transform you can usually ignore it, because the stream stops calling transform until it drains.
Keep CPU work small per chunk, or move it to a worker.
For short stages, an async generator function in pipeline does the same with less ceremony, but a class is easier to unit test and reuse.
javascript
const { Transform, Readable } = require('node:stream');
const { StringDecoder } = require('node:string_decoder');
const { pipeline } = require('node:stream/promises');
class LineSplitter extends Transform {
constructor({ withFlush = true } = {}) {
super({ readableObjectMode: true });
this.decoder = new StringDecoder('utf8');
this.tail = '';
this.withFlush = withFlush;
}
_transform(chunk, encoding, callback) {
const text = this.tail + this.decoder.write(chunk);
const lines = text.split('\n');
this.tail = lines.pop(); // the last piece may be incomplete
for (const line of lines) this.push(line);
callback();
}
_flush(callback) {
if (this.withFlush) {
const rest = this.tail + this.decoder.end();
if (rest) this.push(rest);
}
callback();
}
}
async function collect(withFlush) {
// Chunk boundaries cut a line, and a 2-byte character (é) is split across chunks.
const euro = Buffer.from('caf\u00e9\nlast');
const chunks = [Buffer.from('one\ntw'), Buffer.from('o\nthree\n'), euro.subarray(0, 4), euro.subarray(4)];
const lines = [];
await pipeline(
Readable.from(chunks, { objectMode: false }),
new LineSplitter({ withFlush }),
async function (source) { for await (const line of source) lines.push(line); },
);
return lines;
}
async function main() {
console.log('with flush :', JSON.stringify(await collect(true)));
console.log('without flush:', JSON.stringify(await collect(false)));
}
main();
The input chunks cut a line and a character in the middle. Without flush the last line is lost. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
with flush : ["one","two","three","café","last"]
without flush: ["one","two","three","café"]
Key points
transform() receives chunks, pushes results and calls the callback.
Chunks split data anywhere, so keep the incomplete tail.
flush() emits what remains at the end of input.
Use StringDecoder for multi-byte text.
Call the callback exactly once per chunk.
Common mistakes
Splitting each chunk on newlines without keeping the tail.
Decoding each chunk with toString() and breaking multi-byte characters.
Skipping flush and losing the last line when the file has no final newline.
Calling the callback twice, or not at all on an error path.
Forgetting readableObjectMode when pushing strings you want to keep as separate items.
Follow-ups
How would you handle Windows line endings (\r\n)?
How would you limit the maximum line length to protect memory?
When is an async generator stage better than a Transform class?
Tips
Show the tail buffer idea in one sentence.
Mention flush before the code.
Mention StringDecoder to show you know about multi-byte text.
105.nodejs-0105Hardsenior
What is the difference between Duplex, Transform and PassThrough, and how do you build a Duplex with independent read and write sides?
A Duplex has a readable side and a writable side that are independent, like a socket: what you write is not what you read. A Transform is a Duplex where the output is computed from the input. PassThrough is a Transform that copies input to output. Implement a Duplex with _read and _write (and _final), or build one from a function with Duplex.from.
Full answer
The four stream classes form a family:
Readable: you produce data (_read, push).
Writable: you consume data (_write, _final).
Duplex: both, with no relationship between the two sides. A TCP socket is the standard example. Writes go to the peer, and reads come from the peer.
Transform: a Duplex whose readable side is the result of the writable side (_transform, _flush).
PassThrough: a Transform that does nothing. It is useful as a tap, a placeholder, or a way to connect code that wants a stream to code that produces one later.
Building a Duplex:
Implement _read(size) and call push(data) or push(null) at the end of the readable side.
Implement _write(chunk, encoding, callback) for the writable side.
Optionally implement _final(callback) to run when the writer calls end(), and _destroy for cleanup.
Each side has its own buffer, its own highWaterMark and its own backpressure. allowHalfOpen (default true) means one side can end while the other continues.
Helpers:
Duplex.from(asyncGeneratorFunction) makes a Duplex that reads from the writable side and yields to the readable side.
stream.compose(a, b, c) joins streams into a single Duplex. Writing goes to the first stage and reading comes from the last. It is useful for reusable pipelines that you can pass around.
Duplex.toWeb and Duplex.fromWeb convert to and from Web Streams.
Design tip: if the output depends on the input, use Transform. If two independent flows share one object, such as a protocol connection or a fake device in a test, use Duplex.
javascript
const { Duplex, Transform, PassThrough, Readable, compose } = require('node:stream');
const { pipeline } = require('node:stream/promises');
// A fake device: commands written to it are stored, and it separately "reports" three readings.
class FakeDevice extends Duplex {
constructor() {
super({ encoding: 'utf8' });
this.commands = [];
this.count = 0;
}
_read() {
this.count < 3 ? this.push(`reading-${++this.count}\n`) : this.push(null);
}
_write(chunk, encoding, callback) {
this.commands.push(chunk.toString());
callback();
}
_final(callback) {
this.commands.push('(writer ended)');
callback();
}
}
async function main() {
const device = new FakeDevice();
device.write('start');
device.end('stop');
let output = '';
for await (const piece of device) output += piece;
console.log('written to device :', JSON.stringify(device.commands));
console.log('read from device :', JSON.stringify(output));
// PassThrough copies; Transform changes.
const tap = new PassThrough();
const seen = [];
tap.on('data', (c) => seen.push(c.toString()));
tap.end('same text');
await new Promise((resolve) => tap.on('end', resolve));
console.log('PassThrough output:', seen.join(''));
// compose joins two stages into one Duplex that can be reused.
const upper = new Transform({ transform(c, e, cb) { cb(null, c.toString().toUpperCase()); } });
const exclaim = new Transform({ transform(c, e, cb) { cb(null, c.toString() + '!'); } });
const shout = compose(upper, exclaim);
console.log('compose is a Duplex:', shout instanceof Duplex);
shout.end('hello');
let shouted = '';
for await (const piece of shout) shouted += piece;
console.log('composed result:', shouted);
// Duplex.from with an async generator.
const numbered = Duplex.from(async function* (source) {
let n = 0;
for await (const chunk of source) yield `${++n}:${chunk}`;
});
const parts = [];
await pipeline(Readable.from(['a', 'b']), numbered, async (source) => { for await (const p of source) parts.push(p); });
console.log('Duplex.from result:', parts.join(' '));
}
main();
The device receives commands and produces readings on separate sides. compose and Duplex.from build reusable stages. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
written to device : ["start","stop","(writer ended)"]
read from device : "reading-1\nreading-2\nreading-3\n"
PassThrough output: same text
compose is a Duplex: true
composed result: HELLO!
Duplex.from result: 1:a 2:b
Key points
Duplex has two independent sides; Transform ties output to input.
PassThrough copies input to output unchanged.
A Duplex needs _read and _write, and often _final.
Duplex.from and compose create reusable stream units.
Each side has its own buffer and backpressure.
Common mistakes
Using Duplex when a Transform was meant, and reading data that was never produced.
Forgetting _final, so the writer's end() has no effect on the device.
Ending the readable side with push(null) and expecting the writable side to close.
Not realising that each side has its own highWaterMark.
Calling push() after push(null).
Follow-ups
What does allowHalfOpen change for a socket?
How do you convert a Node stream to a Web Stream?
When would you use PassThrough in real code?
Tips
Use the socket as the example for Duplex.
Say 'two independent sides' clearly.
Mention compose and Duplex.from as modern tools.
106.nodejs-0106Easyfresher
What are the flowing and paused modes of a Readable stream, and how do the 'data' and 'readable' events differ?
A Readable starts paused. Adding a 'data' listener, calling pipe or resume() switches it to flowing mode, where chunks arrive as fast as they are produced. A 'readable' listener keeps it paused and you pull data with read(). Async iteration with for await is the simplest way to consume a stream and respects backpressure.
Full answer
A Readable has an internal buffer. How you consume it decides the mode.
Initial state: readableFlowing is null. Nothing is read from the source.
Flowing: attach a 'data' listener, call pipe(), or call resume(). The stream reads from the source and emits 'data' for every chunk. If you have no consumer ready, chunks can be lost, so attach listeners right away.
Paused: call pause(), or attach a 'readable' listener. Data stays in the buffer. 'readable' tells you data is available, and you call read() in a loop until it returns null.
The 'readable' listener takes priority. If it is attached, 'data' does not flow until the listener is removed.
Which to use:
for await (const chunk of readable) is the modern default. It pulls data, handles errors, and ends cleanly.
pipeline for connecting streams.
'data' for quick scripts and for events that you want to push to listeners as they happen.
'readable' with read(n) when you need to read an exact number of bytes, for example a binary protocol header.
Important rules: do not mix styles on the same stream, always handle 'error', and never rely on 'data' being called before you attach the listener. The legacy 'streams1' pause behaviour is gone, so do not rewrite old code unless needed.
The first lines print readableFlowing in each state. The next lines show the same data read through three styles. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
initial readableFlowing: null
after data listener : true
after pause() : false
'data' event pieces : a,b,c
'readable' pieces : xy,z
for await text : abc
Key points
Readable streams start paused (readableFlowing is null).
'data', pipe and resume() switch to flowing mode.
'readable' keeps the stream paused and you call read().
Prefer for await...of or pipeline.
Common mistakes
Attaching the 'data' listener late and missing chunks.
Mixing 'data' and 'readable' on one stream.
Not handling 'error'.
Calling read() once per 'readable' event instead of looping until null.
Assuming each chunk is one line or one message.
Follow-ups
What does pause() do to a pipe()d stream?
How does read(size) behave when fewer bytes are buffered?
Why is for await safer than the 'data' event?
Tips
Start with the three states of readableFlowing.
Say you prefer for await.
Mention read(n) for binary headers.
107.nodejs-0107Easyfresher
What encoding mistakes happen with Buffers and strings (utf8, hex, base64, binary data), and how do you avoid them?
String length counts UTF-16 units, Buffer length counts bytes, so they differ for non-ASCII text. Invalid utf8 bytes become the replacement character, which makes binary data in utf8 strings lossy. Hex strings with an odd length or bad characters are silently cut. Use base64, base64url or hex for binary data in text, and Buffer.byteLength when you need a byte count.
Full answer
Common traps and the safe habit for each:
Length: 'cafe\u0301'.length counts UTF-16 code units. Buffer.byteLength(text) counts bytes in an encoding. Use bytes for Content-Length, size limits and storage.
Invalid bytes: Buffer.from([0xff]).toString('utf8') does not throw. It returns the replacement character (U+FFFD), and the original byte is gone. Never turn binary data (images, encrypted bytes, hashes) into a utf8 string. Keep it as a Buffer, or encode it with base64 or hex.
Cut characters: slicing a Buffer in the middle of a multi-byte character, or decoding streamed chunks one by one, produces broken text. Decode after joining chunks, or with StringDecoder.
Hex and base64 parsing are forgiving. Buffer.from('abc', 'hex') returns one byte (the odd digit is dropped), and bad characters stop the parsing. Validate the input with a regular expression before decoding.
base64 vs base64url: base64 uses + and / and padding with =. URLs and JWTs use base64url (- and _, no padding). Node supports 'base64url'.
latin1 (binary) maps one byte to one character 0 to 255. It is lossless for bytes but wrong for text.
Emoji and other characters outside the basic plane use 4 bytes in utf8 and two UTF-16 units.
Rules: pick an encoding on purpose, specify it on every conversion, and treat text and bytes as separate types.
javascript
const text = 'caf\u00e9 \u20ac \ud83d\ude00';
console.log('string length:', text.length, '| utf8 bytes:', Buffer.byteLength(text, 'utf8'), '| utf16le bytes:', Buffer.byteLength(text, 'utf16le'));
// Binary data does not survive a trip through a utf8 string.
const binary = Buffer.from([0xff, 0xd8, 0x41, 0x80]);
const viaUtf8 = Buffer.from(binary.toString('utf8'), 'utf8');
console.log('binary as hex :', binary.toString('hex'));
console.log('after utf8 roundtrip:', viaUtf8.toString('hex'), '| equal:', binary.equals(viaUtf8));
console.log('after base64 :', Buffer.from(binary.toString('base64'), 'base64').equals(binary));
// Cutting a multi-byte character.
const euro = Buffer.from('\u20ac'); // 3 bytes
console.log('euro bytes:', euro.length, '| first two bytes decode to', JSON.stringify(euro.subarray(0, 2).toString()));
// Forgiving decoders.
console.log("Buffer.from('abc', 'hex') length:", Buffer.from('abc', 'hex').length);
console.log("Buffer.from('zz12', 'hex') length:", Buffer.from('zz12', 'hex').length);
const isHex = (s) => /^([0-9a-f]{2})+$/i.test(s);
console.log('strict hex check:', isHex('abc'), isHex('abcd'));
// base64 and base64url
const token = Buffer.from([0xfb, 0xff, 0xfe]);
console.log('base64 :', token.toString('base64'));
console.log('base64url:', token.toString('base64url'));
// latin1 keeps bytes but is not text
console.log('latin1 roundtrip equal:', Buffer.from(binary.toString('latin1'), 'latin1').equals(binary));
Every line prints a fact: lengths, a lossy round trip, cut characters and decoders that do not complain. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
string length: 9 | utf8 bytes: 14 | utf16le bytes: 18
binary as hex : ffd84180
after utf8 roundtrip: efbfbdefbfbd41efbfbd | equal: false
after base64 : true
euro bytes: 3 | first two bytes decode to "�"
Buffer.from('abc', 'hex') length: 1
Buffer.from('zz12', 'hex') length: 0
strict hex check: false true
base64 : +//+
base64url: -__-
latin1 roundtrip equal: true
Key points
String length is not byte length.
Invalid utf8 becomes U+FFFD, so binary data is lost in a utf8 string.
Hex and base64 decoding silently drop bad input.
Use base64url for URLs and tokens.
Decode streamed chunks with StringDecoder.
Common mistakes
Using string length to check a byte limit.
Reading an image into a utf8 string.
Sending base64 in a URL without switching to base64url.
Trusting Buffer.from(input, 'hex') to throw on bad input.
Decoding each streamed chunk separately.
Follow-ups
Why can a hash digest not be stored as a utf8 string?
How do you check that a string is valid base64?
What does TextDecoder with fatal: true do?
Tips
Open with 'characters are not bytes'.
Give the utf8 roundtrip as the strongest example.
Mention base64url for tokens.
108.nodejs-0108Easyfresher
How do you watch files for changes in Node.js, and why do you get duplicate events?
fs.watch uses the operating system's notifications and emits 'rename' (create, delete, move) and 'change' events with the file name. One save can produce several events, and the details differ by platform, so debounce per file and re-read the file. fs.watchFile polls and is slower but predictable. node --watch restarts a script on change, and libraries like chokidar smooth over platform differences.
Full answer
Options in Node:
fs.watch(path, options, listener) or the promise version fs.promises.watch(path, { signal }), which returns an async iterator. It uses inotify on Linux, FSEvents on macOS and ReadDirectoryChangesW on Windows. It is efficient, but behaviour differs by platform.
fs.watchFile(path, { interval }, listener): polls stat information. It works on network drives where native events do not, but costs CPU.
node --watch app.js restarts the process when a imported file changes, and node --watch-path=./src targets directories. It is for development.
chokidar and similar libraries normalise events, handle atomic saves and globs. Many tools use it.
Things that surprise people:
Event names are 'rename' and 'change'. 'rename' covers create, delete and move. You must stat the path to know what happened.
One save often produces two or more events, because editors write a temporary file, truncate, write and rename. Debounce by file name (wait 50 to 200 ms of silence) before reacting.
filename can be null on some platforms, so guard for it.
The recursive option works on Linux since Node 20, and on macOS and Windows for a longer time. Test on your platform.
Watching a file that is replaced (an atomic save) can lose the watch on some systems. Watch the directory instead.
Always keep a way to stop the watcher (close() or an AbortSignal) so the process can exit.
The script creates, edits and deletes a file. Several raw events arrive, but the debounce turns each burst into one reaction. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
event kinds seen: change:config.json | rename:config.json
debounced reactions: 2 for config.json
Key points
fs.watch uses OS events and reports 'rename' and 'change'.
One save can fire several events, so debounce per file.
Watch the directory to survive atomic saves.
watchFile polls and works on network drives.
Close watchers or abort them so the process can exit.
Common mistakes
Reacting to every raw event and rebuilding many times.
Assuming 'rename' means only a rename.
Watching a single file and losing it after an atomic save.
Forgetting to close the watcher so the process never exits.
Testing only on one operating system.
Follow-ups
How does node --watch decide what to restart?
How would you watch a large directory tree without hitting limits?
Why can inotify watches run out on Linux?
Tips
Mention duplicate events early.
Say 'debounce' and 'watch the directory'.
Name chokidar as the common library.
109.nodejs-0109Hardsenior
How do you process a very large file efficiently: line counting, parallel byte ranges, and resuming after a crash?
Never read the file into memory. Stream it and keep only counters or small aggregates. For more speed, split the file into byte ranges that start and end on newline boundaries, and process the ranges with createReadStream({ start, end }) in parallel (in workers for CPU work). To resume after a crash, store the byte offset of the last fully processed line and restart from it.
Full answer
Memory is the first limit. readFile on a 5 GB file fails. Streams keep memory flat, but speed and recovery need more design.
Speed
Do the least work per byte. Scanning for newline bytes in raw Buffers is much faster than creating a string per line with readline. Use readline when you need the line text and the file is moderate.
Increase highWaterMark (for example 1 MB) for fewer reads on fast disks.
Parallelism: disks and CPUs allow it. Split the file into N ranges by size. A range boundary can fall inside a line, so move each boundary forward to the next newline. Each range then starts at a line start and ends at a line end. Process ranges in parallel with createReadStream({ start, end }), where end is inclusive.
For CPU heavy parsing use worker_threads, one range per worker. For simple counting, one thread is often limited by the disk.
Combine results from ranges (sums, maps), which should be associative.
Recovery
Track the byte offset after each batch of lines. Write it to a checkpoint file atomically (write a temp file, then rename).
On restart read the offset and open the stream with { start: offset }. Make the processing idempotent, because the last batch may run twice.
Other points: handle the last line without a newline, handle \r\n, do not trust file size to be stable for a growing log, and prefer a database bulk loader (COPY) when the goal is to load data.
javascript
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const readline = require('node:readline');
// Build a deterministic 200,000-line "access log": status,bytes
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'bigfile-'));
const file = path.join(dir, 'access.log');
const statuses = [200, 200, 200, 404, 500];
const lines = [];
for (let i = 0; i < 200000; i++) lines.push(`${statuses[i % 5]},${(i * 37) % 1000}`);
fs.writeFileSync(file, lines.join('\n')); // no newline at the end on purpose
// Process one byte range: count lines and sum bytes (field 2).
async function processRange(start, end, from = 0) {
let count = 0, total = 0;
const rl = readline.createInterface({ input: fs.createReadStream(file, { start: start + from, end, highWaterMark: 1 << 20 }), crlfDelay: Infinity });
for await (const line of rl) { count++; total += Number(line.split(',')[1]); }
return { count, total };
}
// Move a boundary forward to just after the next newline.
async function nextLineStart(handle, pos, size) {
const buf = Buffer.alloc(4096);
while (pos < size) {
const { bytesRead } = await handle.read(buf, 0, buf.length, pos);
if (bytesRead === 0) break;
const i = buf.subarray(0, bytesRead).indexOf(10);
if (i !== -1) return pos + i + 1;
pos += bytesRead;
}
return size;
}
async function main() {
const size = fs.statSync(file).size;
const handle = await fs.promises.open(file, 'r');
// Single pass for the expected answer.
const whole = await processRange(0, size - 1);
console.log('single pass :', whole);
// Four aligned ranges, processed in parallel.
const parts = 4;
const starts = [0];
for (let p = 1; p < parts; p++) starts.push(await nextLineStart(handle, Math.floor((size * p) / parts), size));
await handle.close();
const ranges = starts.map((s, i) => [s, (starts[i + 1] ?? size) - 1]);
const results = await Promise.all(ranges.map(([s, e]) => processRange(s, e)));
const sum = results.reduce((a, r) => ({ count: a.count + r.count, total: a.total + r.total }), { count: 0, total: 0 });
console.log('parallel sum:', sum, '| same as single pass:', sum.count === whole.count && sum.total === whole.total);
// Resume: pretend we crashed after the first range, with its offset saved.
const checkpoint = ranges[0][1] + 1;
const first = await processRange(0, checkpoint - 1);
const rest = await processRange(checkpoint, size - 1);
console.log('resume from byte', checkpoint, '-> total matches:', first.count + rest.count === whole.count && first.total + rest.total === whole.total);
fs.rmSync(dir, { recursive: true });
}
main();
A 200,000 line file is created, then counted once, in four aligned parallel ranges, and in two parts split at a checkpoint. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
single pass : { count: 200000, total: 99900000 }
parallel sum: { count: 200000, total: 99900000 } | same as single pass: true
resume from byte 394500 -> total matches: true
Key points
Stream and keep aggregates only.
Raw byte scanning beats creating a string per line.
Align range boundaries to newlines and use inclusive end.
Combine per-range results with associative operations.
Checkpoint byte offsets for resume, and make work idempotent.
Common mistakes
Using readFile or readFileSync for large input.
Splitting ranges at fixed byte offsets and cutting lines in two.
Forgetting that the end option of createReadStream is inclusive.
Parallelising a disk-bound job and getting no speedup.
Writing the checkpoint non-atomically and reading a half-written file.
Follow-ups
How would you run each range in a worker thread?
How do you handle quoted CSV fields that contain newlines when you split by ranges?
How can you read the last 10 lines of a big log quickly?
Tips
Lead with 'never load the whole file'.
Explain the aligned boundary in one sentence.
Mention idempotent processing for resume.
110.nodejs-0110Easyfresher
How do you stream newline-delimited JSON (NDJSON) in Node.js, and how do you handle bad lines?
NDJSON stores one JSON value per line, so you can read and write it as a stream without holding everything in memory. Read with readline (or a line splitter), call JSON.parse inside try/catch for each line, and record the line number of bad lines. Write by calling JSON.stringify(item) + '\n'. A normal JSON array must be parsed completely before use.
Full answer
A JSON array is one value. JSON.parse needs the whole text, so a 2 GB file needs 2 GB or more of memory. NDJSON (also JSON Lines, .jsonl) puts one complete JSON value on each line. Each line stands alone, so you can process it as soon as it arrives.
Reading:
Use readline.createInterface({ input }) and for await (const line of rl). readline handles chunk boundaries and \r\n.
Parse each line with JSON.parse in try/catch. One bad line should not stop a job that has millions of lines. Count the failures and save the line number and a short sample for review.
Skip empty lines (a trailing newline is common).
Cap the line length if the input is untrusted.
Writing:
Write JSON.stringify(item) + '\n' for each item. JSON.stringify never puts a raw newline inside a string, because newlines in strings are escaped, so one item stays on one line.
Use a Writable stream and respect backpressure (pipeline with a generator is simple).
Where it is used: log files, exports from databases and search engines, streaming API responses such as event feeds, and bulk import formats.
Compare with alternatives: CSV is smaller but flat, and Server-Sent Events adds framing for browsers. For one huge JSON array you need a streaming parser library, which is more complex, so prefer NDJSON when you control the format.
javascript
const { Readable } = require('node:stream');
const readline = require('node:readline');
const { pipeline } = require('node:stream/promises');
// Input arrives in arbitrary pieces, and line 3 is damaged.
const pieces = [
'{"name":"Asha","marks":78}\n{"name":"Ra',
'vi","marks":64}\n{"name":"Meera","marks":\n',
'\n{"name":"Kabir","marks":91}',
];
async function main() {
const rl = readline.createInterface({ input: Readable.from(pieces), crlfDelay: Infinity });
const good = [];
const bad = [];
let lineNumber = 0;
for await (const line of rl) {
lineNumber++;
if (!line.trim()) continue; // skip empty lines
try {
good.push(JSON.parse(line));
} catch (err) {
bad.push({ line: lineNumber, sample: line.slice(0, 20) });
}
}
console.log('parsed:', good.map((r) => r.name).join(', '));
console.log('bad lines:', JSON.stringify(bad));
// Writing NDJSON: one stringify per line. A newline inside a value is escaped.
const out = [];
await pipeline(
Readable.from(good.concat({ name: 'Zoya\nTwo', marks: 55 })),
async function* (source) { for await (const item of source) yield JSON.stringify(item) + '\n'; },
async function (source) { for await (const text of source) out.push(text); },
);
console.log('output lines:', out.join('').trimEnd().split('\n').length);
console.log('last line:', out[out.length - 1].trimEnd());
}
main();
The input is split in awkward places and one line is broken. The good lines are parsed and the bad line is reported by number. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
parsed: Asha, Ravi, Kabir
bad lines: [{"line":3,"sample":"{\"name\":\"Meera\",\"mar"}]
output lines: 4
last line: {"name":"Zoya\nTwo","marks":55}
Key points
NDJSON is one JSON value per line, so it streams.
Parse each line separately and keep going after a bad line.
JSON.stringify escapes newlines, so one item is one line.
readline handles chunk boundaries.
Common mistakes
Reading the whole file and using JSON.parse on a single array.
Letting one bad line crash the whole job.
Splitting on '\n' by hand and ignoring chunk boundaries.
Pretty-printing JSON, which puts one value on many lines.
Not skipping the empty last line.
Follow-ups
How is NDJSON different from a JSON array in an HTTP API?
How would you limit the maximum line size?
How would you stream a large JSON array without NDJSON?
Tips
Say 'one value per line' in the first sentence.
Mention bad line handling.
Compare with a JSON array.
111.nodejs-0111Mediummid
Why is splitting CSV text on commas not enough, and how do you stream CSV with csv-parse, including quoted fields and bad rows?
CSV allows commas, quotes and even line breaks inside quoted fields, so line.split(',') breaks on real data. A parser such as csv-parse follows the format (RFC 4180), runs as a Transform stream, can map rows to objects with columns, and can skip or report bad rows. Use it inside pipeline or for await so memory stays flat.
Full answer
The CSV format is simple only until real data arrives:
A field can be quoted: "Sharma, Asha". The comma inside the quotes is data.
A quote inside a quoted field is written twice, as in "She said ""hi"" there".
A quoted field can contain a line break, so one record can span two lines. Splitting by line before parsing breaks it.
Files can start with a byte order mark (BOM), use semicolons or tabs, or have rows with the wrong number of fields.
csv-parse (from the csv project) is a Transform stream. Bytes go in, records come out. Important options:
columns: true uses the header row as property names and returns objects.
cast: true converts numbers and dates, or give a function for exact control. Be careful with IDs like 007.
trim: true removes spaces around fields.
bom: true removes a leading BOM.
delimiter for ; or tab.
relax_column_count and skip_records_with_error with on_skip decide what happens to bad rows. Never skip silently: count them and log the line number.
The error object has code, lines and record details to report to the user.
Use it with stream/promises pipeline or for await so backpressure is respected. The sync API (csv-parse/sync) is fine for small files in scripts only. Validate each record afterwards (for example with zod), because a parser checks syntax, not meaning.
javascript
const { parse } = require('csv-parse');
const { Readable } = require('node:stream');
// A header, a quoted comma, doubled quotes, a line break inside quotes, and one row with a missing field.
const text = [
'name,city,note,marks',
'Asha,"Pune, India","She said ""hi"" there",78',
'Ravi,Delhi,"two',
'lines",64',
'Meera,Mumbai,only three fields',
'Kabir,Chennai,ok,91',
].join('\n');
async function main() {
// The naive way:
const naive = text.split('\n').map((line) => line.split(','));
console.log('naive row 2 field count:', naive[1].length, '(should be 4)');
const skipped = [];
const parser = Readable.from([text.slice(0, 40), text.slice(40)]).pipe(parse({
columns: true,
trim: true,
cast: (value, context) => (context.column === 'marks' ? Number(value) : value),
skip_records_with_error: true,
on_skip: (err) => skipped.push({ code: err.code, line: err.lines }),
}));
const records = [];
for await (const record of parser) records.push(record);
for (const r of records) console.log(JSON.stringify(r));
console.log('skipped:', JSON.stringify(skipped));
}
main();
The text is cut into two chunks in the middle of a row. The parser still returns three correct records and reports the bad row with its line number. Install first with npm install csv-parse (run here with csv-parse 7.0.3). Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
naive row 2 field count: 5 (should be 4)
{"name":"Asha","city":"Pune, India","note":"She said \"hi\" there","marks":78}
{"name":"Ravi","city":"Delhi","note":"two\nlines","marks":64}
{"name":"Kabir","city":"Chennai","note":"ok","marks":91}
skipped: [{"code":"CSV_RECORD_INCONSISTENT_COLUMNS","line":5}]
Key points
Quoted fields can contain commas, quotes and line breaks.
csv-parse is a Transform stream and fits pipeline and for await.
columns turns rows into objects.
Decide on purpose what happens to bad rows, and count them.
Validate parsed values separately.
Common mistakes
Using split(',') on real CSV data.
Splitting the file by lines first and breaking multi-line fields.
Loading a whole big CSV with the sync API.
Skipping bad rows silently.
Using cast: true and turning an ID such as 007 into 7.
Follow-ups
How do you handle a file with a BOM or a different delimiter?
How would you validate each record before inserting it into a database?
How do you write CSV safely, including values that start with = or +?
Tips
Give the three tricky cases: comma, quote, line break.
Say that the parser is a Transform and fits pipeline.
Mention bad row reporting.
112.nodejs-0112Easyfresher
Assume this file is run as a CommonJS script with node app.js.
```js
async function a() {
console.log('a start');
await b();
console.log('a end');
}
async function b() {
console.log('b');
}
console.log('script start');
setTimeout(() => console.log('timeout'), 0);
a();
Promise.resolve().then(() => console.log('promise'));
process.nextTick(() => console.log('nextTick'));
console.log('script end');
```
What does it print, and why?
Synchronous code runs first, including the body of an async function up to its first await. Then process.nextTick callbacks run, then promise microtasks (the code after await is one of them), and only then timers. So the order is script start, a start, b, script end, nextTick, a end, promise, timeout.
Full answer
Work through it in the order the engine does.
Step 1, the synchronous part (the call stack runs until it is empty):
script start is printed.
setTimeout registers a timer callback. It will run in the timers phase later.
a() is called. It prints a start, then calls b(), which prints b and returns a resolved promise. The await then pauses a() and schedules the rest of a() (the line a end) as a microtask. Control returns to the caller.
Promise.resolve().then(...) schedules the 'promise' callback as a microtask. It was queued after the continuation of a(), so it comes later.
process.nextTick schedules a callback in the nextTick queue.
script end is printed.
Step 2, after the current operation finishes:
Node empties the nextTick queue first: nextTick is printed.
Then the microtask queue is emptied in order: a end, then promise.
Step 3, the event loop continues and the timers phase runs the timer: timeout.
Rules to remember: code before the first await runs synchronously. await always yields, even for an already resolved promise. nextTick has priority over promise microtasks in CommonJS. Microtasks always finish before the loop moves on to timers.
Common wrong answers put a end before script end, or promise before nextTick.
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, same on two runs):
script start
a start
b
script end
nextTick
a end
promise
timeout
Key points
Code before the first await runs synchronously.
nextTick runs before promise microtasks in CommonJS.
The continuation after await is a microtask.
Timers run after the microtask queue is empty.
Common mistakes
Thinking that await b() makes b run later. The call itself is synchronous.
Putting 'a end' before 'script end'.
Treating nextTick and promise callbacks as the same queue.
Expecting the timer with 0 ms to run before microtasks.
Follow-ups
What changes if the file is an ES module?
What changes if b() is not async?
Where would setImmediate appear in this output?
Tips
Narrate the call stack in phases.
State the three queues in priority order.
Do not guess the order. Say which queue each line goes to.
113.nodejs-0113Easyfresher
Several timers are created in loops and with different delays.
```js
for (var i = 0; i < 3; i++) setTimeout(() => console.log('var', i), 0);
for (let j = 0; j < 3; j++) setTimeout(() => console.log('let', j), 0);
setTimeout(() => console.log('10 ms'), 10);
setTimeout(() => console.log('1 ms'), 1);
setTimeout(() => console.log('0 ms'), 0);
```
What does it print, and why?
The var loop prints 3 three times because all callbacks share one variable that is 3 when they run. The let loop prints 0, 1, 2 because each iteration has its own binding. Node treats a delay of 0 as 1 ms, so the 1 ms and 0 ms timers keep their creation order, and the 10 ms timer runs last.
Full answer
Two separate ideas are tested.
Closures and loops:
var is function scoped. There is one i. The callbacks run after the loop ended, when i is 3. Output: var 3, three times.
let is block scoped, and a for loop creates a fresh binding for each iteration. Each callback keeps its own j. Output: let 0, let 1, let 2.
Timer order:
Node clamps a delay of 0 (or less than 1) to 1 ms. So setTimeout(fn, 0) and setTimeout(fn, 1) are the same.
Timers with the same delay are kept in a list in creation order and run in that order.
The var and let callbacks (1 ms each, created first), then '1 ms', then '0 ms', all belong to the same group, so they print in creation order. The 10 ms timer runs later.
The delay is a minimum, not a promise. If the process is busy, callbacks run late, but the order of timers that are due stays by due time and then by creation.
Final order: var 3, var 3, var 3, let 0, let 1, let 2, 1 ms, 0 ms, 10 ms.
A frequent follow-up asks how to fix the var version without let: use an IIFE, bind, or pass the value as an extra argument to setTimeout (setTimeout(fn, 0, i)).
The output shows the closure results first and then the timers in the order they were created, with 10 ms last. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
var 3
var 3
var 3
let 0
let 1
let 2
1 ms
0 ms
10 ms
Key points
var shares one binding; let creates one per iteration.
A 0 ms delay becomes 1 ms in Node.
Equal delays run in creation order.
A delay is a minimum, not an exact time.
Common mistakes
Expecting var to print 0, 1, 2.
Expecting the 0 ms timer to run before the 1 ms timer.
Thinking that a delay is exact.
Using setTimeout order to coordinate work.
Follow-ups
How do you fix the var loop without using let?
What does setTimeout(fn, 0, i) do?
How is setImmediate different from a 0 ms timer?
Tips
Split the answer in two: closures and timer order.
Give the fix for the var case.
Say that timers are minimums.
114.nodejs-0114Easyfresher
This chain mixes return values, a thrown error, catch, finally and a then with a non-function argument.
```js
Promise.resolve(1)
.then((v) => { console.log('then 1:', v); return v + 1; })
.then((v) => { console.log('then 2:', v); throw new Error('boom'); })
.then(() => console.log('skipped'))
.catch((e) => { console.log('catch:', e.message); return 'recovered'; })
.finally(() => { console.log('finally'); return 'ignored'; })
.then((v) => console.log('then 3:', v))
.then(() => Promise.resolve('x').then(Promise.resolve('not a function')))
.then((v) => console.log('non-function then ->', v));
```
What does it print, and why?
Each then returns a new promise. A returned value becomes the next value, and a thrown error skips then handlers until a catch. catch can recover by returning a value. finally runs either way, passes the previous value through, and ignores its own return value. A then with a non-function argument is ignored and the value passes through.
Full answer
Trace the value (or error) along the chain.
Start: resolved with 1.
then 1 prints 1 and returns 2.
then 2 prints 2 and throws. The chain is now rejected.
The next then has only a success handler, so it is skipped. Nothing is printed for 'skipped'.
catch prints boom and returns 'recovered'. The chain is fulfilled again with that value.
finally prints finally. It receives no argument. Its return value ('ignored') does not change the chain. If finally threw an error, or returned a rejected promise, the chain would reject.
then 3 receives 'recovered' and prints it.
The last two lines: .then(Promise.resolve('not a function')) passes a promise, not a function, as the handler. The spec says to ignore non-function handlers, so 'x' passes through to the end.
Output:
then 1: 1, then 2: 2, catch: boom, finally, then 3: recovered, non-function then -> x
Other facts: .catch(fn) is .then(undefined, fn). The second argument of then handles errors from earlier in the chain but not from the first handler of the same then. A handler that returns a promise makes the chain wait for it.
The output lines follow the value along the chain. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
then 1: 1
then 2: 2
catch: boom
finally
then 3: recovered
non-function then -> x
Key points
A returned value flows to the next then.
A thrown error skips success handlers until a catch.
finally passes the value through and ignores its return value.
Non-function arguments to then are ignored.
Common mistakes
Expecting 'skipped' to print.
Thinking the finally return value replaces the chain value.
Passing a promise to then instead of a function.
Forgetting to return inside then and passing undefined on.
Follow-ups
What changes if finally throws?
What is the difference between .then(a, b) and .then(a).catch(b)?
What happens with an error thrown inside catch?
Tips
Trace one value across the chain, step by step.
State the finally rule explicitly.
Mention the non-function rule.
115.nodejs-0115Mediummid
Two queues, process.nextTick and promise microtasks, schedule work inside each other. Assume a CommonJS file first.
```js
Promise.resolve().then(() => {
console.log('promise 1');
process.nextTick(() => console.log('nextTick inside promise'));
}).then(() => console.log('promise 2'));
process.nextTick(() => {
console.log('nextTick 1');
Promise.resolve().then(() => console.log('promise inside nextTick'));
});
process.nextTick(() => console.log('nextTick 2'));
setTimeout(() => console.log('timeout'), 0);
```
What does it print, and why?
In CommonJS the nextTick queue is emptied first, then the microtask queue is emptied completely, then the loop repeats if either queue got new work. The output is nextTick 1, nextTick 2, promise 1, promise inside nextTick, promise 2, nextTick inside promise, timeout. In an ES module the first run starts inside a promise job, so promise callbacks come before nextTick callbacks.
Full answer
Node runs two queues after each operation (after the main script, and after every callback):
Drain the nextTick queue.
Drain the promise microtask queue completely, including microtasks added while draining.
If the nextTick queue has new items, go to step 1. Otherwise continue with the event loop.
Applying it to the CommonJS file:
The synchronous part registers: a promise reaction (promise 1), two nextTick callbacks and a timer.
Step 1: nextTick 1 prints, and queues a microtask. nextTick 2 prints.
Step 2: the microtask queue holds [promise 1, promise inside nextTick]. promise 1 prints and schedules a nextTick and the promise 2 reaction. The queue continues: promise inside nextTick, then promise 2. The microtask queue stays busy until empty.
In an ES module, the whole module body runs as part of a promise job, so the microtask queue is drained first. The nextTick callbacks wait until it is empty. That is why the same code prints in a different order. The snippet runs the puzzle in both modes.
Starvation: because both queues are drained fully, a callback that keeps scheduling nextTick (or promises) forever blocks timers and I/O. Prefer setImmediate to yield between large pieces of work.
The same puzzle runs in two child processes, once as CommonJS and once as an ES module, so the two orders can be compared. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
CommonJS: nextTick 1 > nextTick 2 > promise 1 > promise inside nextTick > promise 2 > nextTick inside promise > timeout
ES module: promise 1 > promise 2 > nextTick 1 > nextTick 2 > nextTick inside promise > promise inside nextTick > timeout
Key points
nextTick queue first, then the whole microtask queue, then repeat.
Work added during draining is processed before the loop continues.
ES modules start inside a promise job, so microtasks go first.
Endless nextTick or promise recursion starves timers and I/O.
Common mistakes
Thinking nextTick and promises share one queue.
Stopping the trace after the first microtask.
Assuming ES modules and CommonJS behave the same.
Using recursive nextTick for long loops.
Follow-ups
How do you split a long loop so that I/O can run in between?
What does queueMicrotask do compared with nextTick?
Why can a nextTick loop freeze a server?
Tips
Say the three-step rule.
Mention the ES module difference.
Name starvation as the practical risk.
116.nodejs-0116Hardsenior
Two async functions return the same promise in different ways, and a counter chain measures when each one settles.
```js
async function viaReturn() { return Promise.resolve('x'); }
async function viaAwait() { return await Promise.resolve('x'); }
const order = [];
viaReturn().then(() => order.push('return promise'));
viaAwait().then(() => order.push('return await'));
Promise.resolve().then(() => order.push('tick 1'))
.then(() => order.push('tick 2'))
.then(() => order.push('tick 3'))
.then(() => order.push('tick 4'));
setTimeout(() => console.log(order.join(' > ')), 0);
```
What does it print, and why?
Returning a promise from an async function takes about two extra microtask ticks, because the engine has to adopt the thenable. return await settles earlier. The printed order is tick 1, return await, tick 2, return promise, tick 3, tick 4. The difference rarely matters, but it explains subtle ordering bugs, and return await is needed inside try/catch.
Full answer
This puzzle measures microtask ticks with a chain that adds one step per tick.
Why return Promise.resolve('x') is slower:
An async function's own promise is resolved with the return value. If the value is a thenable (a promise), the spec does not use it directly. It queues a job that calls promise.then(resolveOuter, rejectOuter) (tick 1). When the inner promise settles, the then callback runs and resolves the outer promise (tick 2). Only then can the outer promise's own handlers run (tick 3).
That is about two extra ticks compared with returning a plain value.
Why return await is earlier:
await of a native promise uses one tick. After it, the function returns a plain value, so the outer promise resolves right away, and its handler runs on the next tick.
Order from the output: tick 1, return await, tick 2, return promise, tick 3, tick 4.
Practical consequences:
This almost never matters for correctness, but tests that assert on the exact order of logs can break when someone changes return to return await.
return await has a real purpose inside try/catch. Without await the function returns before the promise settles, so a rejection escapes the catch block.
Promise.resolve(p) returns p itself if p is a native promise, so wrapping does not add ticks.
Any object with a then method is a thenable. await and resolve adopt it, and a thenable's then method gets called in a microtask job.
Do not write code that depends on tick counts. Know the rule so you can explain a surprising log order.
The printed line shows the order in which the two async functions and the numbered ticks completed. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
tick 1 > return await > tick 2 > return promise > tick 3 > tick 4
Key points
Returning a promise from an async function costs about two extra ticks.
return await settles earlier but is needed for try/catch.
Promise.resolve(p) returns p when p is a native promise.
Never depend on exact tick counts in real code.
Common mistakes
Claiming that all promise callbacks run in creation order.
Removing return await inside a try block and losing the catch.
Writing tests that depend on microtask tick counts.
Forgetting that thenables are adopted through an extra job.
Follow-ups
Why does return await matter inside try/catch?
What does await do with a non-promise value?
How would you prove the tick counts with a counter chain?
Tips
Say 'adopting a thenable' to show depth.
Give the practical point about try/catch.
Admit that tick counts should not drive design.
117.nodejs-0117Mediummid
Four promise combinators receive tasks that finish at different times, and some of them fail.
```js
const wait = (ms, value, fail) =>
new Promise((resolve, reject) => setTimeout(() => (fail ? reject(new Error(value)) : resolve(value)), ms));
const show = (p) => p.then((v) => 'ok ' + JSON.stringify(v), (e) => 'error ' + e.message);
(async () => {
console.log('all ->', await show(Promise.all([wait(30, 'a'), wait(10, 'b'), wait(20, 'c')])));
console.log('all fails ->', await show(Promise.all([wait(30, 'a'), wait(10, 'b', true), wait(20, 'c')])));
console.log('race ->', await show(Promise.race([wait(30, 'a'), wait(10, 'b', true), wait(20, 'c')])));
console.log('any ->', await show(Promise.any([wait(30, 'a'), wait(10, 'b', true), wait(20, 'c')])));
console.log('any fails ->', await show(Promise.any([wait(10, 'x', true), wait(20, 'y', true)])));
console.log('allSettled ->', (await Promise.allSettled([wait(10, 'a'), wait(20, 'b', true)])).map((r) => r.status).join(','));
})();
```
What does it print, and why?
Promise.all keeps input order in its result and rejects on the first failure. Promise.race settles with whichever promise settles first, success or failure. Promise.any fulfils with the first success and ignores failures, and rejects with an AggregateError if all fail. Promise.allSettled never rejects and reports every outcome.
Full answer
Predict with a timeline of 10, 20 and 30 ms.
all: all three succeed. The result array follows the input order, not the finish order: ["a","b","c"].
all fails: b fails at 10 ms. The result is a rejection with error b right away. The other tasks keep running but their results are ignored. all does not cancel them.
race: b settles first (at 10 ms) with a failure, so race rejects with error b. race copies the first settlement, whether success or failure.
any: b fails at 10 ms and is ignored. c succeeds at 20 ms. any fulfils with "c". Task a finishes later and is ignored.
any fails: both fail, so any rejects with an AggregateError. Its message is 'All promises were rejected', and the individual errors are in .errors.
allSettled: never rejects. It resolves with objects { status, value } or { status, reason }. Statuses: fulfilled, rejected.
Which to use:
all: when every result is needed, and one failure means the whole job failed.
allSettled: when you want every outcome and you handle partial failure.
race: for timeouts (race against a timer) or the first response. Remember that losers are not cancelled, so pair it with an AbortController.
any: for redundancy, such as asking several mirrors and taking the first good answer.
One more trap: tasks start when they are created, not when you pass them to the combinator. Creating the array starts everything at once.
Each line uses a different combinator on tasks of 10, 20 and 30 ms. Failures are turned into text so one line does not stop the script. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
all -> ok ["a","b","c"]
all fails -> error b
race -> error b
any -> ok "c"
any fails -> error All promises were rejected
allSettled -> fulfilled,rejected
Key points
all keeps input order and rejects on the first failure.
race copies the first settlement, even a failure.
any ignores failures until one succeeds, else AggregateError.
allSettled never rejects.
None of them cancels the slower tasks.
Common mistakes
Expecting Promise.all results in finish order.
Believing that Promise.all cancels the other tasks.
Using race for a timeout without aborting the slow work.
Forgetting that any rejects with an AggregateError.
Starting tasks inside a loop that awaits each one and losing the parallelism.
Follow-ups
How do you implement a timeout with Promise.race and an AbortController?
How do you limit concurrency, since Promise.all starts everything at once?
What does the errors property of an AggregateError hold?
Tips
Walk through the timeline.
Say 'nothing is cancelled'.
Give one use case per combinator.
118.nodejs-0118Mediummid
An EventEmitter has one async listener between two normal ones.
```js
const EventEmitter = require('node:events');
const emitter = new EventEmitter();
emitter.on('job', () => console.log('listener 1'));
emitter.on('job', async () => {
console.log('listener 2 start');
await null;
console.log('listener 2 end');
});
emitter.on('job', () => console.log('listener 3'));
console.log('before emit');
emitter.emit('job');
console.log('after emit');
```
What does it print, and why?
emit calls listeners synchronously in registration order and does not wait for promises. The async listener runs until its first await, then emit continues with listener 3 and returns. The rest of the async listener runs later as a microtask. If an async listener rejects, nobody catches it, so it becomes an unhandled rejection unless captureRejections is turned on.
Full answer
EventEmitter is synchronous. emit() loops over the listeners and calls each one. It ignores return values, including promises.
Output of the puzzle: before emit, listener 1, listener 2 start, listener 3, after emit, listener 2 end.
The async listener starts running at once, up to await null.
The await schedules the rest as a microtask, and the async function returns a pending promise to emit, which ignores it.
listener 3 runs, emit returns, and the main code prints after emit.
When the main code finishes, the microtask runs: listener 2 end.
The error problem:
A throw inside a normal listener propagates out of emit() into the caller, and later listeners do not run.
A rejection inside an async listener does not reach the caller. It becomes an unhandledRejection, which crashes modern Node by default.
Option: new EventEmitter({ captureRejections: true }) (or events.captureRejections = true). A rejected promise from a listener is then sent to the 'error' event, or to a Symbol.for('nodejs.rejection') method if you define one. Always add an 'error' listener.
Option: wrap async listeners in your own try/catch and log the error.
Design rules: never rely on emit() waiting for async work. If the caller must wait, use a different pattern, such as a method that returns Promise.all of the handlers, or events.once for one event.
The first block is the puzzle. The next two blocks show a failing async listener with and without captureRejections. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
before emit
listener 1
listener 2 start
listener 3
after emit
listener 2 end
unhandled rejection: async failure
'error' event received: async failure
Key points
emit runs listeners synchronously and ignores returned promises.
The async listener resumes after emit returns.
A rejection in an async listener becomes an unhandled rejection.
captureRejections routes it to the 'error' event.
Do not rely on emit() to wait for async work.
Common mistakes
Expecting emit() to wait for an async listener.
Letting an async listener throw with no protection.
Using captureRejections without an 'error' listener.
Assuming a throw in a listener is caught by emit.
Using the order of async listener completion as logic.
Follow-ups
How does events.once let you wait for an event?
What happens to the remaining listeners when one of them throws?
How would you make emit return a promise that waits for all handlers?
Tips
Say 'emit is synchronous' first.
Trace the order, then add the error case.
Mention captureRejections by name.
119.nodejs-0119Hardsenior
Latency spikes hit every endpoint when one particular input arrives. How can a regular expression block the event loop, and how do you diagnose and fix it?
A regular expression with nested quantifiers, such as /^(a+)+$/, can take exponential time on a near-match input. JavaScript regex runs on the main thread, so one request freezes timers, I/O and every other request. Diagnose with event loop delay metrics and a CPU profile, then fix by using a linear pattern, limiting input length, a safe regex engine, or running risky matching in a worker with a time limit.
Full answer
The scenario: p99 latency jumps to seconds, CPU for one process is at 100 percent, and all endpoints are slow at once, not only one route. Logs show nothing wrong. A single request is blocking the loop.
Why a regex can do this:
V8 uses a backtracking engine. For a pattern like (a+)+$ on aaaa...ab, the engine tries every way to split the a's before it fails. Time grows exponentially with the input length: about 2 to the power n.
The match runs synchronously on the main thread, so nothing else (timers, sockets, other requests) runs meanwhile.
Danger signs: nested quantifiers (a+)+, (a|aa)+, (.) , alternations that overlap, and patterns applied to user input without length limits. Email, URL and 'validate everything' regexes are common sources.
Diagnosis:
Track event loop delay (monitorEventLoopDelay) and alert on its p99 and max.
Take a CPU profile (node --cpu-prof, or the inspector) during the spike. The hot frame is the RegExp exec or the function calling it.
Log the length and a hash of inputs for slow requests. Add timing around suspicious regex calls.
Fixes, in order of preference:
Rewrite the pattern to be unambiguous (^a+$). Avoid nested quantifiers.
Limit the input length before matching (for example 254 characters for an email).
Use a parser or a validation library instead of a custom regex.
Use a linear-time engine (such as RE2 through a package) for untrusted patterns or input.
Run risky work in a worker thread and terminate the worker after a time limit.
Add a regex test with an evil input to the test suite and a lint rule that detects unsafe patterns.
Node regexes have no built-in timeout, so prevention matters more than reaction.
javascript
const { Worker } = require('node:worker_threads');
const { performance } = require('node:perf_hooks');
const evilInput = 'a'.repeat(26) + 'b';
function lagOf(work) {
// Schedule a 10 ms timer, run the work synchronously, and measure how late the timer is.
return new Promise((resolve) => {
const start = performance.now();
setTimeout(() => resolve(performance.now() - start - 10), 10);
work();
});
}
async function main() {
const lag1 = await lagOf(() => /^(a+)+$/.test(evilInput));
console.log('nested quantifier delays the timer by more than 100 ms:', lag1 > 100);
const lag2 = await lagOf(() => /^a+$/.test(evilInput));
console.log('linear pattern delays the timer by less than 20 ms:', lag2 < 20);
// Run the dangerous pattern in a worker and stop it after 50 ms.
const worker = new Worker(`
const { parentPort, workerData } = require('node:worker_threads');
parentPort.postMessage(/^(a+)+$/.test(workerData));
`, { eval: true, workerData: evilInput });
const start = performance.now();
const outcome = await Promise.race([
new Promise((resolve) => worker.once('message', (ok) => resolve('finished: ' + ok))),
new Promise((resolve) => setTimeout(() => resolve('timed out'), 50)),
]);
await worker.terminate();
console.log('worker result:', outcome);
console.log('main thread stayed responsive (took under 300 ms):', performance.now() - start < 300);
}
main();
The same input is tested with a bad pattern, a good pattern and a bad pattern inside a worker with a time limit. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
nested quantifier delays the timer by more than 100 ms: true
linear pattern delays the timer by less than 20 ms: true
worker result: timed out
main thread stayed responsive (took under 300 ms): true
Key points
Nested quantifiers can make regex time exponential.
The match runs on the main thread and freezes everything.
Event loop delay and CPU profiles point to the culprit.
Fix with a linear pattern and an input length limit.
A worker with terminate() can enforce a time limit.
Common mistakes
Validating user input with a complicated regex and no length limit.
Looking for the problem in the database instead of the CPU profile.
Believing that async code makes a regex non-blocking.
Adding a timeout around the request and expecting it to stop the regex.
Copying an email regex from the internet without testing evil input.
Follow-ups
How does RE2 avoid exponential time?
How would you alert on this in production?
How can a ReDoS attack be rate limited at the edge?
Tips
Describe the symptom as 'every endpoint slow at once'.
Explain backtracking in one sentence.
Give the fix list in order.
120.nodejs-0120Hardsenior
What do three typical Node.js memory leak case studies look like (an unbounded map, listeners on a shared emitter, a forgotten timer), and how do you confirm each fix?
Case 1: a module-level Map keeps an entry per request and nothing deletes it. Case 2: each request adds a listener to a long-lived emitter and never removes it. Case 3: a setInterval is never cleared and its closure keeps request data alive. Confirm with heapUsed after a forced GC before and after the load, and fix with bounded caches, once or removeListener, and clearInterval.
Full answer
A leak is memory that stays reachable but is no longer needed. Reachability comes from roots: module variables, long-lived objects, active timers, and event listeners.
Case 1: the unbounded map
Symptom: the heap grows linearly with traffic and never drops. A heap snapshot shows a Map with millions of entries.
Cause: a module-level Map or object used as a cache or session store, with no size limit or expiry.
Fix: delete entries when the request ends, use a bounded LRU with a TTL, or use WeakMap when keys are objects that have their own lifetime.
Case 2: listeners on a shared emitter
Symptom: MaxListenersExceededWarning appears, or someone raises the limit to silence it, and memory grows. Each listener closure holds its request data.
Cause: emitter.on(...) inside a request handler on an emitter that lives for the whole process (a pool, a message bus, process).
Fix: use once, remove the listener in a finally block, or use events.once with an AbortSignal. Never silence the warning without understanding it.
Case 3: the forgotten timer
Symptom: memory grows and CPU usage creeps up because the intervals keep running.
Cause: setInterval created per request or per connection, with no clearInterval when the connection closes. The callback closure keeps its captured objects alive.
Fix: store the timer id and clear it on close, use AbortSignal-based timers, and call unref() for timers that must not keep the process alive.
How to prove a fix:
Run a repeatable load (for example 1000 simulated requests), force garbage collection (node --expose-gc), then compare heapUsed with the baseline.
Repeat the run a few times. A real leak keeps growing and a cache fills up and stops.
Compare two heap snapshots and look at the retained size and the retainer path.
Add the load test to CI for services that had a leak before.
javascript
const { spawnSync } = require('node:child_process');
// The experiment runs in a child process so that --expose-gc can be used.
const experiment = `
const EventEmitter = require('node:events');
const REQUESTS = 1000;
const heapMB = () => { global.gc(); global.gc(); const m = process.memoryUsage(); return (m.heapUsed + m.arrayBuffers) / 1048576; };
const payload = () => Buffer.alloc(16 * 1024);
function measure(run) {
const before = heapMB();
const cleanup = run();
const during = heapMB() - before;
if (cleanup) cleanup();
return during;
}
// Case 1: a module-level Map
const sessions = new Map();
const leakyMap = () => { for (let i = 0; i < REQUESTS; i++) sessions.set('r' + i, payload()); return () => sessions.clear(); };
const fixedMap = () => { for (let i = 0; i < REQUESTS; i++) { sessions.set('r' + i, payload()); sessions.delete('r' + i); } };
// Case 2: listeners on a shared emitter
const bus = new EventEmitter();
bus.setMaxListeners(0); // this switches the warning off, which is how such leaks stay hidden
const leakyListeners = () => { for (let i = 0; i < REQUESTS; i++) { const data = payload(); bus.on('tick', () => data.length); } return () => bus.removeAllListeners('tick'); };
const fixedListeners = () => { for (let i = 0; i < REQUESTS; i++) { const data = payload(); const fn = () => data.length; bus.on('tick', fn); bus.off('tick', fn); } };
// Case 3: timers that are never cleared
const timers = [];
const leakyTimers = () => { for (let i = 0; i < REQUESTS; i++) { const data = payload(); timers.push(setInterval(() => data.length, 1e6)); } return () => timers.forEach(clearInterval); };
const fixedTimers = () => { for (let i = 0; i < REQUESTS; i++) { const data = payload(); clearInterval(setInterval(() => data.length, 1e6)); } };
const cases = [['map', leakyMap, fixedMap], ['listeners', leakyListeners, fixedListeners], ['timers', leakyTimers, fixedTimers]];
for (const [name, leaky, fixed] of cases) {
const leakedMB = measure(leaky);
const fixedMB = measure(fixed);
console.log(name.padEnd(10), 'leaky keeps more than 8 MB:', leakedMB > 8, '| fixed keeps less than 2 MB:', fixedMB < 2);
}
process.exit(0);
`;
const run = spawnSync(process.execPath, ['--expose-gc', '-e', experiment], { encoding: 'utf8' });
process.stdout.write(run.stdout);
if (run.status !== 0) console.log('child failed', run.stderr);
A child process simulates 1000 requests of 16 KB each for every case, forces garbage collection, and compares memory with and without the fix. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
map leaky keeps more than 8 MB: true | fixed keeps less than 2 MB: true
listeners leaky keeps more than 8 MB: true | fixed keeps less than 2 MB: true
timers leaky keeps more than 8 MB: true | fixed keeps less than 2 MB: true
Key points
Leaks are reachable but useless memory.
Module-level maps, shared emitters and timers are the usual roots.
Do not silence MaxListenersExceededWarning without fixing the cause.
Prove a fix with forced GC before and after a repeatable load.
Bounded caches, once or removeListener, and clearInterval are the fixes.
Common mistakes
Raising setMaxListeners instead of removing the listener.
Reading memory without forcing GC and calling normal growth a leak.
Using an object as an unbounded cache.
Creating timers per request and relying on the process to end.
Taking one heap snapshot instead of two to compare.
Follow-ups
How would you find which of these three leaks you have using heap snapshots?
When is a WeakMap or WeakRef the right fix?
How do you make a leak test stable enough to run in CI?
Tips
Name the root in each case: module, emitter, timer.