Questions 1–20 of 200 · 0 of 20 on this page marked learned
1.nodejs-0001Easyfresher
What is Node.js, and is it really single-threaded?
Node.js is a runtime that runs JavaScript outside the browser using the V8 engine and a C library called libuv. Your JavaScript runs on one main thread, but file, network and some crypto work is handed to the operating system or a thread pool, so Node as a whole is not limited to one thread.
Full answer
Node.js is not a language or a framework. It is a runtime: a program that embeds the V8 JavaScript engine (the same engine as Chrome) and adds things a browser does not have, such as file access, TCP sockets and child processes. Those extra abilities come from libuv, a C library that talks to the operating system.
Your JavaScript code runs on one thread, the main thread. Only one piece of JavaScript executes at any moment, so two callbacks never change the same variable at the same time. That removes most locking problems.
Waiting is different. When you ask for a file or a network response, Node gives the job to the operating system or to libuv's thread pool (4 threads by default) and carries on. When the job finishes, its callback is queued, and the event loop runs it on the main thread when the thread is free. Think of a canteen with one cashier (the main thread) and a kitchen with several cooks (the OS and thread pool). The cashier never cooks, so the queue keeps moving.
So "single-threaded" is true for your JavaScript and misleading for the whole process. A running Node process has several threads: V8 helper threads for garbage collection, the libuv pool, and any worker_threads you start yourself. The real limit is that a long calculation on the main thread blocks every other request.
javascript
const fs = require('node:fs');
const { isMainThread, threadId } = require('node:worker_threads');
console.log('1. start, main thread:', isMainThread, 'threadId:', threadId);
fs.readFile(__filename, () => {
// The read happened in the background, but this callback runs on the main thread.
console.log('3. readFile callback, main thread:', isMainThread, 'threadId:', threadId);
});
console.log('2. end of script (the read has not been reported yet)');
The file read is done by libuv in the background, but the callback still runs on the JavaScript thread. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
1. start, main thread: true threadId: 0
2. end of script (the read has not been reported yet)
3. readFile callback, main thread: true threadId: 0
Key points
Your JavaScript runs on one main thread, one callback at a time.
V8 runs the JavaScript. libuv provides the event loop, the thread pool and the OS calls.
I/O waits do not occupy the main thread, so one thread can serve many connections.
CPU-heavy JavaScript blocks everything, so it must be split up or moved to worker threads.
Common mistakes
Saying Node.js is a language or a framework.
Believing that a Node process has exactly one thread in total.
Thinking async code runs in parallel on several JavaScript threads. Callbacks are interleaved, not simultaneous.
Using Node for heavy CPU work in the request path without worker threads.
Follow-ups
Which Node.js operations use the libuv thread pool and which do not?
How does Node handle 10,000 open connections with one JavaScript thread?
What would you change if one endpoint needs 200 ms of pure CPU work per request?
Tips
Describe Node as V8 plus libuv in one sentence, then explain what runs where.
Use the cashier and kitchen picture only if it helps. Interviewers care more about the blocking consequence.
Mention worker_threads early when the question moves to CPU-bound work.
2.nodejs-0002Mediummid
What are the phases of the Node.js event loop, and in what order do they run?
Each loop iteration runs these phases in order: timers, pending callbacks, idle and prepare, poll, check and close callbacks. Timers run expired setTimeout and setInterval callbacks, poll collects I/O events, check runs setImmediate callbacks, and close runs cleanup callbacks such as a socket's close event.
Full answer
The event loop is a loop inside libuv. On every turn (an iteration or "tick") it visits a fixed list of phases. Each phase has its own queue of callbacks, and the loop runs the queue until it is empty or a limit is reached, then moves on.
Timers. Runs callbacks of setTimeout and setInterval whose time has passed. The delay is a minimum, not a promise.
Pending callbacks. Runs some deferred system callbacks, for example certain TCP errors.
Idle and prepare. Used internally by Node. You never schedule work here.
Poll. Gets new I/O events and runs their callbacks (file reads, socket data). If nothing is ready, the loop may wait here, but it will not wait past the next timer, and it will not wait at all if setImmediate callbacks are queued.
Check. Runs setImmediate callbacks. This is why setImmediate runs right after the poll phase.
Close callbacks. Runs cleanup callbacks such as socket.on('close').
Between phases, and in modern Node between individual callbacks, Node empties the process.nextTick queue and then the promise microtask queue. These are not phases. They run whenever the current JavaScript stack finishes.
If there is no pending timer, I/O or immediate, the loop has nothing left to do and the process exits. That is why a script with only a finished promise ends by itself.
javascript
// A timer asks for 20 ms, but the script then blocks for 80 ms.
const start = Date.now();
setTimeout(() => {
console.log('timers phase: callback ran, delay was at least 80 ms:', Date.now() - start >= 80);
}, 20);
setImmediate(() => {
console.log('check phase: setImmediate callback');
});
while (Date.now() - start < 80) {
// busy wait: the loop cannot start while this runs
}
console.log('main script finished');
Once the script ends, the loop starts at the timers phase. The 20 ms timer has already expired, so it runs before the check phase, even though it was also late. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
main script finished
timers phase: callback ran, delay was at least 80 ms: true
check phase: setImmediate callback
Key points
Order: timers, pending callbacks, idle/prepare, poll, check, close callbacks.
Timers are minimum delays. An expired timer waits until the loop reaches the timers phase.
Poll handles I/O, check runs setImmediate, close handles cleanup events.
nextTick and promise callbacks are microtask queues, not phases.
Common mistakes
Listing the phases but not saying what each one runs.
Believing setTimeout(fn, 20) runs exactly after 20 ms.
Treating process.nextTick as a phase of the loop.
Saying the loop starts at the poll phase after the main script.
Follow-ups
Where does the loop wait when there is nothing to do, and what stops it from waiting forever?
Why does Node drain the nextTick and promise queues between callbacks?
What happens to the loop if a callback in the poll phase takes 2 seconds?
Tips
Draw the six boxes and name one example callback for each.
State clearly that the loop is inside libuv, not inside V8.
Be ready to explain why a late timer is normal under load.
3.nodejs-0003Mediummid
What is the difference between process.nextTick, promise callbacks, setImmediate and setTimeout?
process.nextTick callbacks run first after the current operation, then promise callbacks (microtasks), both before the loop moves on. setImmediate runs in the check phase of the current iteration, and setTimeout runs in the timers phase of a later iteration.
Full answer
Node keeps two microtask-style queues that are emptied as soon as the running JavaScript finishes:
The nextTick queue. Callbacks added with process.nextTick(fn).
The promise microtask queue. Callbacks from .then, .catch, await, and queueMicrotask.
Node empties the whole nextTick queue first, then the promise queue, and repeats until both are empty. Only then does the event loop go on to the next callback or phase.
setImmediate and setTimeout are real loop callbacks. setImmediate runs in the check phase, directly after poll. setTimeout runs in the timers phase, which comes at the start of the next iteration.
The order of setTimeout(fn, 0) and setImmediate(fn) at the top level of a script is not fixed. It depends on how fast the process starts. Inside an I/O callback the order is fixed: setImmediate always runs first, because the loop is in the poll phase and check comes next.
A practical warning: a nextTick callback that keeps scheduling another nextTick callback starves the loop, because Node never reaches I/O. A recursive setImmediate does not starve it.
javascript
const fs = require('node:fs');
// Inside an I/O callback the order is the same every time.
fs.readFile(__filename, () => {
setTimeout(() => console.log('5. setTimeout 0 (next loop iteration)'), 0);
setImmediate(() => console.log('4. setImmediate (check phase)'));
Promise.resolve().then(() => console.log('3. promise then'));
process.nextTick(() => console.log('2. process.nextTick'));
console.log('1. synchronous code in the callback');
});
The snippet runs inside an I/O callback on purpose, because that is where the order is guaranteed. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
1. synchronous code in the callback
2. process.nextTick
3. promise then
4. setImmediate (check phase)
5. setTimeout 0 (next loop iteration)
Key points
nextTick runs before promise callbacks, and both run before the loop continues.
setImmediate runs in the check phase. setTimeout runs in the timers phase.
Top-level order of setTimeout 0 and setImmediate is not guaranteed.
Recursive nextTick can starve I/O. Prefer setImmediate for yielding.
Common mistakes
Saying setImmediate runs 'immediately', before nextTick.
Claiming setTimeout 0 always runs before setImmediate, or the opposite, at the top level.
Using recursive process.nextTick for a long task and freezing the server.
Mixing up nextTick (Node only) with queueMicrotask (a standard API).
Follow-ups
Why is the top-level order of setTimeout 0 and setImmediate unpredictable?
How does await map to these queues?
How would you split a 1 million item loop so the server stays responsive?
Tips
Memorise the order: sync, nextTick, promises, immediate, timeout (in an I/O callback).
Run the snippet yourself and change the order of the calls. The output stays the same.
Say that nextTick is older and the Node docs now recommend queueMicrotask in most cases.
4.nodejs-0004Hardsenior
Why does the order of setTimeout(fn, 0) and setImmediate(fn) change between runs, and when is it guaranteed?
At the top level of a script, setTimeout 0 is really a 1 ms timer. Whether that millisecond has passed when the loop first enters the timers phase depends on process speed, so either callback can run first. Inside an I/O callback, or inside a timer callback, setImmediate always runs first.
Full answer
Node turns a delay of 0 into 1 ms. When the main script ends, the event loop starts at the timers phase. If at least 1 ms has passed since setTimeout was called, the timer fires first. If the machine was fast, the timers phase finds nothing ready, the loop moves on, and the check phase runs setImmediate first. Startup cost, system load and CPU speed change the result from run to run.
The order is fixed in two cases:
Inside an I/O callback (poll phase). The next phase is check, so setImmediate runs before the timer, which must wait for the next iteration.
Inside a timer callback. The loop is in the timers phase. A new setTimeout 0 is due at least 1 ms later, so it waits for the next iteration, while check comes next in the current one, so setImmediate runs first.
There is a second, newer rule worth knowing. Since Node 11, the nextTick and promise queues are emptied after each individual callback, not only after a whole phase. Before Node 11, two setImmediate callbacks would both run before any promise callback. Today a promise callback created in the first immediate runs before the second immediate.
If you need an order, do not depend on timers. Chain the work with promises or callbacks so the order is explicit.
javascript
const fs = require('node:fs');
// Case 1: microtasks run between two callbacks of the same phase (Node 11 and later).
function caseOne(next) {
setImmediate(() => {
console.log('A1. first immediate');
Promise.resolve().then(() => console.log('A2. promise from first immediate'));
});
setImmediate(() => {
console.log('A3. second immediate');
next();
});
}
// Case 2: inside a timer callback, setImmediate beats a new setTimeout 0.
function caseTwo() {
setTimeout(() => {
setTimeout(() => console.log('B3. inner setTimeout 0'), 0);
setImmediate(() => console.log('B2. inner setImmediate'));
console.log('B1. outer timer callback');
}, 10);
}
caseOne(caseTwo);
Both cases are fixed in order on current Node versions. The top-level setTimeout vs setImmediate race is not printed here because it is not stable. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
A1. first immediate
A2. promise from first immediate
A3. second immediate
B1. outer timer callback
B2. inner setImmediate
B3. inner setTimeout 0
Key points
setTimeout 0 is treated as 1 ms, so the first-iteration result depends on timing.
Inside an I/O callback, setImmediate always runs first.
Inside a timer callback, setImmediate also runs first in practice, because check follows timers.
Microtasks run after every callback since Node 11, not after every phase.
Common mistakes
Saying the order is 'random'. It is timing dependent, and fixed in the cases above.
Writing tests that depend on the top-level order.
Forgetting that a zero delay is clamped to 1 ms.
Using old advice that all immediates run before any promise callback.
Follow-ups
How would you rewrite code that depends on the timer vs immediate order?
What changed in Node 11 about microtasks and timers?
Why can a very busy process make setTimeout 0 fire later than setImmediate?
Tips
Explain the 1 ms clamp, then the two guaranteed cases.
Show you can reason about it from the phase order instead of memorising outputs.
Offer the fix: make the dependency explicit with promises.
5.nodejs-0005Easyfresher
What does it mean to block the event loop, and how do you avoid it?
Blocking the event loop means running long synchronous code on the main thread, so no other callback, timer or request can run until it finishes. Avoid it by using async APIs, splitting work into small chunks, or moving CPU-heavy work to worker threads or another service.
Full answer
Because all JavaScript callbacks share one thread, a callback that takes 500 ms makes every other request wait 500 ms. Nothing else can run while it works: not a timer, not a new connection, not a health check. In a busy API this looks like a sudden jump in latency for everyone.
Typical causes:
Synchronous APIs such as fs.readFileSync or execSync inside a request handler.
Large JSON.parse or JSON.stringify calls on megabyte-sized data.
A regular expression with catastrophic backtracking.
A long for loop (sorting, hashing, image or PDF work) over a large array.
Synchronous crypto such as pbkdf2Sync.
Ways to avoid it:
Use the async version of every I/O API.
Split a long loop into chunks and give control back between chunks with setImmediate.
Move real CPU work to worker_threads or to a separate service or queue.
Measure with the event loop delay histogram from perf_hooks or with a profiler, so you see the problem before users do.
Synchronous calls are fine at start-up, in CLI scripts and in build tools, because no one is waiting on the loop there.
javascript
const TOTAL = 60_000_000;
function blocking() {
let sum = 0;
for (let i = 0; i < TOTAL; i++) sum += i;
return sum;
}
function chunked(done) {
let sum = 0;
let i = 0;
function step() {
const end = Math.min(i + 2_000_000, TOTAL);
for (; i < end; i++) sum += i;
if (i < TOTAL) setImmediate(step); // let other callbacks run between chunks
else done(sum);
}
step();
}
function run(label, work) {
return new Promise((resolve) => {
let timerRanEarly = false;
const finish = (sum) => {
console.log(label, 'sum =', sum, '| 1 ms timer ran before the work finished:', timerRanEarly);
resolve();
};
setTimeout(() => { timerRanEarly = true; }, 1);
if (work === blocking) finish(blocking());
else chunked(finish);
});
}
(async () => {
await run('blocking:', blocking);
await run('chunked: ', chunked);
})();
The timer is only able to run during the chunked version. The numbers are fixed, so the output does not depend on machine speed. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
blocking: sum = 1799999970000000 | 1 ms timer ran before the work finished: false
chunked: sum = 1799999970000000 | 1 ms timer ran before the work finished: true
Key points
One long synchronous task delays all other work in the process.
Common causes: sync APIs, huge JSON, bad regex, long loops, sync crypto.
Fixes: async APIs, chunking with setImmediate, worker threads, a queue.
Sync APIs are acceptable at start-up and in scripts.
Common mistakes
Using readFileSync or JSON.parse on large input inside a request handler.
Thinking that wrapping heavy work in a Promise or an async function makes it non-blocking. It still runs on the main thread.
Chunking with a very large chunk size, which still blocks for a long time.
Ignoring regular expression backtracking as a cause.
Follow-ups
How would you detect event loop lag in production?
Why does async/await not help with CPU-heavy work?
When would you pick chunking over a worker thread?
Tips
Say the key sentence: async does not mean parallel for JavaScript code.
Name the event loop delay metric (perf_hooks.monitorEventLoopDelay) to sound production-aware.
Give one safe use of a sync API to show balanced judgement.
6.nodejs-0006Hardsenior
What is the libuv thread pool, which operations use it, and how can it become a bottleneck?
libuv keeps a pool of 4 worker threads by default for work that has no non-blocking OS API, such as most fs calls, dns.lookup, zlib and crypto functions like pbkdf2 and scrypt. If more than 4 such tasks run at once, the extra ones queue, so a few slow tasks can delay unrelated file reads. UV_THREADPOOL_SIZE changes the size.
Full answer
Network sockets use the operating system's event notification (epoll on Linux), so they do not need extra threads. Some work has no such mechanism, and libuv runs it on a pool of worker threads instead. This pool is shared by the whole process.
Typical users of the pool:
Most fs operations (readFile, stat, open and so on).
dns.lookup (not dns.resolve, which uses the network).
zlib compression and decompression.
crypto functions such as pbkdf2, scrypt, randomBytes and randomFill.
The default size is 4 and the maximum is 1024. Set it with the UV_THREADPOOL_SIZE environment variable, before the first use of the pool. The best place is the command that starts the process, for example UV_THREADPOOL_SIZE=8 node server.js.
The bottleneck appears when slow tasks fill the pool. Suppose four password hashes with scrypt run at once. A fifth task, even a tiny fs.stat, waits for a free thread, so a file read can take hundreds of milliseconds even though the disk is idle. The symptom is high latency in fs or dns calls while CPU usage is moderate.
Raising the pool size helps only up to the number of CPU cores for CPU-bound jobs. Better options are limiting how many hashes run at once, using a separate worker thread pool for heavy jobs, or using a dedicated service for password hashing.
javascript
const { spawnSync } = require('node:child_process');
// The child shows what happens with a pool of one thread and a pool of four.
const childCode = `
const crypto = require('node:crypto');
const fs = require('node:fs');
const order = [];
// A heavy job takes the pool thread(s).
for (let i = 0; i < 4; i++) {
crypto.pbkdf2('password', 'salt', 300000, 64, 'sha512', () => order.push('hash ' + i));
}
// A tiny job that also needs a pool thread.
fs.stat(__filename === '[eval]' ? '/' : __filename, () => order.push('fs.stat'));
setTimeout(() => console.log('fs.stat finished ahead of all hash jobs:', order[0] === 'fs.stat'), 3000);
`;
for (const size of ['1', '4', '8']) {
const r = spawnSync(process.execPath, ['-e', childCode], {
env: { ...process.env, UV_THREADPOOL_SIZE: size },
encoding: 'utf8',
});
console.log('pool size', size + ':', r.stdout.trim());
}
Each child process gets its own pool size. With four heavy jobs queued first, a pool of 1 or 4 leaves the tiny fs.stat call waiting for a free thread, while a pool of 8 has a spare thread for it right away. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
pool size 1: fs.stat finished ahead of all hash jobs: false
pool size 4: fs.stat finished ahead of all hash jobs: false
pool size 8: fs.stat finished ahead of all hash jobs: true
Key points
Pool of 4 threads by default, shared by fs, dns.lookup, zlib and several crypto functions.
Sockets do not use the pool.
Slow tasks can delay unrelated fs and dns calls by queueing.
UV_THREADPOOL_SIZE must be set before the pool is first used.
Common mistakes
Thinking all async APIs run on the thread pool. Network I/O does not.
Setting UV_THREADPOOL_SIZE inside the script after the pool already started.
Setting the pool size far above the CPU core count for CPU-bound jobs.
Confusing dns.lookup (pool) with dns.resolve (network).
Follow-ups
How would you notice that the thread pool is saturated in production?
Why is it risky to run many scrypt calls in an HTTP handler?
How is this pool different from worker_threads?
Tips
Link the symptom (slow fs or dns while CPU is calm) to the cause.
Mention that the default size 4 is not tied to the number of cores.
Offer two fixes: limit concurrency and isolate heavy work.
7.nodejs-0007Easyfresher
What are the four types of streams in Node.js, and why use a stream instead of reading the whole file?
Node has Readable, Writable, Duplex and Transform streams. A stream processes data in small chunks, so memory stays low and work can start before all data has arrived. Reading a whole file with readFile needs memory for the full file and waits until all of it is loaded.
Full answer
A stream is an object that moves data piece by piece. The four types:
Readable: a source you read from, such as fs.createReadStream or an incoming HTTP request.
Writable: a destination you write to, such as fs.createWriteStream or an HTTP response.
Duplex: both readable and writable, with two independent sides. A TCP socket is the usual example.
Transform: a duplex stream whose output is computed from its input, such as zlib.createGzip or a stream that changes text to upper case.
Why streams? Suppose a 2 GB log file must be compressed and sent to a client. With fs.readFile the process needs 2 GB of memory and the client gets nothing until the whole file is read. With streams, a 64 KB chunk is read, compressed and sent, then the next chunk. Memory stays near 64 KB, the first bytes arrive quickly, and slow clients are handled through backpressure.
Streams are also a design tool. You can connect small stages (read, decrypt, unzip, parse, save) with stream.pipeline, and each stage stays simple.
For small files, readFile is simpler and perfectly fine. Use streams when data is large, unbounded (uploads, logs, sockets) or arrives over time.
A readable, a transform and a writable are joined with pipeline, which also handles errors and cleanup. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
pipeline finished
MATHS: 78
PHYSICS: 91
CHEMISTRY: 85
Key points
Readable, Writable, Duplex and Transform are the four types.
Streams process chunks, so memory use stays flat for big data.
Output can start before input ends, which lowers latency.
Use readFile for small files and streams for large or unbounded data.
Common mistakes
Treating a Duplex and a Transform as the same thing. A Transform's output is derived from its input.
Using readFile for very large files or for uploads.
Using .pipe() chains without error handlers.
Forgetting that stream chunks are Buffers unless an encoding or object mode is set.
Follow-ups
What is object mode?
How does a stream decide how big each chunk is?
Why can an HTTP request be a stream and a response be a stream?
Tips
Give one example of each type from the core modules.
State both benefits of streaming: low memory and low latency.
Mention pipeline early, because it shows you know how to build stages safely.
8.nodejs-0008Mediummid
What is backpressure in Node.js streams, and how do you handle it?
Backpressure is the signal that a consumer cannot take data as fast as the producer sends it. A Writable returns false from write() when its internal buffer reaches highWaterMark, and the producer should stop until the 'drain' event. pipe() and pipeline() do this automatically.
Full answer
Every stream has an internal buffer. The size limit is highWaterMark (64 KB for byte streams since Node 22, 16 KB before that, and 16 objects in object mode). The limit is a hint, not a hard stop.
When you call writable.write(chunk), Node adds the chunk to the buffer and returns a boolean. true means "the buffer is below the limit, keep going". false means "the buffer is full, please stop". If you ignore false and keep writing, the data piles up in memory. A fast file reader feeding a slow network client can fill gigabytes of RAM that way.
The correct pattern is:
Call write().
If it returns false, stop writing.
Wait for the 'drain' event, then continue.
On the reading side the same idea exists. When pipe or pipeline sees false from the destination, it pauses the readable. On drain it resumes it. You get this for free when you use pipe, pipeline or async iteration with await.
Backpressure matters most when the producer is faster than the consumer, for example reading a local disk and writing to a slow HTTP client, or reading a CSV and inserting rows into a database that handles 500 rows per second.
javascript
const { Writable } = require('node:stream');
const { once } = require('node:events');
// A slow consumer: each chunk needs 5 ms. The buffer limit is 10 bytes.
function makeSlowWriter() {
return new Writable({
highWaterMark: 10,
write(chunk, encoding, callback) {
setTimeout(callback, 5);
},
});
}
// 1. Watch the return value.
const probe = makeSlowWriter();
console.log('write #1 returned', probe.write('12345678'));
console.log('write #2 returned', probe.write('12345678'));
// 2. A producer that respects backpressure.
async function produce(writer, count) {
let pauses = 0;
for (let i = 0; i < count; i++) {
if (!writer.write('12345678')) {
pauses++;
await once(writer, 'drain'); // wait until the buffer empties
}
}
writer.end();
await once(writer, 'finish');
return pauses;
}
produce(makeSlowWriter(), 6).then((pauses) => {
console.log('producer paused', pauses, 'times while writing 6 chunks');
});
Each chunk is 8 bytes and the limit is 10 bytes, so every second write fills the buffer and makes the producer wait. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
write #1 returned true
write #2 returned false
producer paused 3 times while writing 6 chunks
Key points
write() returns false when the buffer reaches highWaterMark.
Stop writing on false and continue on 'drain'.
pipe and pipeline apply backpressure automatically.
Ignoring it causes unbounded memory growth.
Common mistakes
Calling write() in a loop and never checking the return value.
Thinking highWaterMark is a hard memory cap. It only triggers the false signal.
Listening for 'drain' without stopping the loop first.
Reading a whole file into memory and then calling res.write on it in one call.
Follow-ups
How does pipeline apply backpressure between three stages?
Why did Node raise the default byte highWaterMark from 16 KB to 64 KB in version 22?
What happens to a Readable when its pipe destination is slow?
Tips
Explain the three-step pattern: write, check false, wait for drain.
Mention that async iteration (for await) and pipeline handle it for you.
Name a real symptom: memory climbing while a slow client downloads a file.
9.nodejs-0009Mediummid
Why is stream.pipeline preferred over readable.pipe(writable)?
pipe() forwards data and backpressure, but it does not forward errors or destroy the other streams. If one stage fails, the others can stay open and leak file handles or sockets. pipeline() connects the stages, passes the first error to one callback, and destroys all the streams.
Full answer
Both pipe and pipeline move data from a readable stream to a writable stream and respect backpressure. The difference is what happens when something goes wrong.
With pipe, each stream has its own 'error' event, and an error in one stream is not passed on. When the destination errors, the source is simply unpiped and left open. When the source errors, the destination is not ended. You must attach an error handler to every stream and destroy the others yourself. If you forget, a file descriptor or a socket stays open until the process ends, and an unhandled 'error' event can crash the process.
pipeline(...streams, callback) fixes this:
It listens for errors and close events on every stream.
On the first error it destroys all streams, so no handle is left open.
It calls the callback once, with the error or with nothing on success.
A promise version exists in node:stream/promises, which works well with async/await.
It also accepts async generator functions as middle stages.
For new code, use pipeline from node:stream/promises. Keep pipe for quick experiments.
javascript
const { Readable, Transform, Writable, pipeline } = require('node:stream');
function build() {
const source = Readable.from(['a', 'b', 'c', 'd']);
const failing = new Transform({
transform(chunk, encoding, callback) {
if (chunk.toString() === 'c') callback(new Error('bad record: c'));
else callback(null, chunk);
},
});
const sink = new Writable({ write(chunk, encoding, callback) { callback(); } });
return { source, failing, sink };
}
// 1. pipe: the error stays on the middle stream.
const a = build();
a.failing.on('error', (e) => console.log('pipe: error seen only on the middle stream:', e.message));
a.source.pipe(a.failing).pipe(a.sink);
setTimeout(() => {
console.log('pipe: source destroyed?', a.source.destroyed);
// 2. pipeline: one callback, everything is cleaned up.
const b = build();
pipeline(b.source, b.failing, b.sink, (err) => {
console.log('pipeline: callback got:', err.message);
console.log('pipeline: source destroyed?', b.source.destroyed, '| sink destroyed?', b.sink.destroyed);
});
}, 50);
After the same failure, the piped source stays open, while pipeline destroys every stream. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
pipe: error seen only on the middle stream: bad record: c
pipe: source destroyed? false
pipeline: callback got: bad record: c
pipeline: source destroyed? true | sink destroyed? true
Key points
Both respect backpressure.
pipe does not forward errors or destroy streams.
pipeline calls one callback and destroys every stream on the first error.
stream/promises gives an awaitable pipeline.
Common mistakes
Adding an error handler to only one stream in a pipe chain.
Assuming the source closes itself when the destination fails.
Calling the callback-style pipeline inside an async function and forgetting to wait for it.
Catching errors with try/catch around pipe(). The errors are events, not exceptions.
Follow-ups
How do you cancel a pipeline from outside?
What does stream.finished do?
How do async generators work as pipeline stages?
Tips
Show the failure case in the answer, not only the definition.
Say 'file descriptor leak' to name a concrete risk of pipe.
Use require('node:stream/promises') in modern code samples.
10.nodejs-0010Easyfresher
How do you read a large file line by line in Node.js without loading it all into memory?
Create a read stream with fs.createReadStream and pass it to readline.createInterface. The interface emits one line at a time and supports for await...of, so memory use stays small whatever the file size.
Full answer
fs.readFile loads the entire file into one Buffer. For a 5 GB log this fails or slows the whole process. Reading in chunks with a stream avoids it, but chunks do not end on line breaks, so a line can be cut between two chunks.
The readline module solves that. It reads from any readable stream, keeps the partial line until the rest arrives, and gives you complete lines. The interface is async iterable, so the code is a normal loop with backpressure handled for you.
Details worth knowing:
Set crlfDelay: Infinity so that "\r\n" is treated as a single line break.
Lines do not include the line break.
Pass an encoding to createReadStream only if you need something other than UTF-8 handling by readline.
If you also need to stop early (find the first match), call rl.close() or break out of the loop, then destroy the stream.
For CSV with quoted fields that contain line breaks, a plain line split is not enough. Use a CSV parser stage in a pipeline.
javascript
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const readline = require('node:readline');
async function main() {
// Create a small sample file with Windows line endings.
const file = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'marks-')), 'marks.txt');
fs.writeFileSync(file, 'asha,78\r\nravi,91\r\nmeera,85\r\n');
const rl = readline.createInterface({
input: fs.createReadStream(file),
crlfDelay: Infinity,
});
let total = 0;
let count = 0;
for await (const line of rl) {
const [name, marks] = line.split(',');
console.log('line', ++count + ':', name, marks);
total += Number(marks);
}
console.log('average marks:', (total / count).toFixed(2));
}
main();
The sample file is created in a temporary folder, so the snippet runs anywhere. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
line 1: asha 78
line 2: ravi 91
line 3: meera 85
average marks: 84.67
Key points
Use readline with fs.createReadStream.
for await (const line of rl) gives complete lines and applies backpressure.
Set crlfDelay: Infinity for Windows line endings.
A plain split on newline breaks CSV fields that contain newlines.
Common mistakes
Using readFileSync(...).split('\n') on a huge file.
Not setting crlfDelay and getting empty lines on Windows files.
Forgetting that the loop variable is a string, so numbers need Number().
Reading a file with readline and then also reading the same stream elsewhere.
Follow-ups
How would you count lines in a 10 GB file quickly?
How do you read only the last 10 lines of a big file?
What changes if the file is gzip compressed?
Tips
Say that readline takes care of lines split across chunks.
Mention for await (modern) before the old 'line' event.
Point out the CSV exception to show you know the limits.
11.nodejs-0011Hardsenior
How would you process a multi-gigabyte CSV with constant memory, and where does highWaterMark and object mode come in?
Build a pipeline of small stages: a byte source, a line splitter that keeps the partial last line between chunks, a parser that outputs one object per row, and a sink that applies backpressure. Memory stays near highWaterMark times the number of stages, no matter how big the file is.
Full answer
The goal is that memory depends on the number of stages and their buffers, never on the file size. A good design has four parts.
A byte source such as fs.createReadStream. Chunks are 64 KB by default (16 KB before Node 22) and cut the file at random points, even in the middle of a line or a multi-byte character.
A line splitter. It joins the leftover text of the previous chunk with the new chunk, splits on newlines, yields all complete lines, and keeps the last piece for the next round. When using strings, decode with the stream's encoding or a StringDecoder so a character is not cut in half.
A parser that turns a line into an object. This stage can run in object mode, where highWaterMark counts objects (16 by default) instead of bytes.
A sink that does the real work, such as batching 1,000 rows per database insert. If the sink is slow, backpressure travels back through the stages up to the file read.
Async generator functions make this short, because pipeline accepts them as stages and handles backpressure between them. Tune highWaterMark only after measuring. A larger value means fewer wake-ups but more memory per stage. Also batch rows before slow I/O, because one insert per row is usually the real bottleneck.
Error handling matters at this size. Use pipeline so a failing stage destroys the file handle, and decide what to do with a bad row (skip and count, or fail fast).
javascript
const { pipeline } = require('node:stream/promises');
const { Readable } = require('node:stream');
// Source: a generator that makes 200,000 rows lazily, like reading a big file.
function* rows(n) {
for (let i = 1; i <= n; i++) yield `${i},${i % 100}\n`;
}
// Stage 1: cut the text into 1000-character chunks (lines get split on purpose).
async function* chunks(source) {
let buffer = '';
for await (const part of source) {
buffer += part;
while (buffer.length >= 1000) {
yield buffer.slice(0, 1000);
buffer = buffer.slice(1000);
}
}
if (buffer) yield buffer;
}
// Stage 2: rebuild whole lines and yield one parsed marks value per row.
async function* parse(source) {
let tail = '';
for await (const chunk of source) {
const lines = (tail + chunk).split('\n');
tail = lines.pop(); // the last piece may be an unfinished line
for (const line of lines) yield Number(line.split(',')[1]);
}
if (tail) yield Number(tail.split(',')[1]);
}
async function main() {
let count = 0;
let sum = 0;
// Stage 3: the sink consumes the values one by one.
await pipeline(Readable.from(rows(200000)), chunks, parse, async function (source) {
for await (const marks of source) {
count++;
sum += marks;
}
});
console.log('rows:', count, '| sum of marks:', sum);
}
main();
The expected sum is 2,000 full cycles of 0 to 99, which is 9,900,000, so a lost partial line would show up as a wrong number. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
rows: 200000 | sum of marks: 9900000
Key points
Memory is the sum of stage buffers, not the file size.
A line splitter must keep the partial last line between chunks.
Object mode counts highWaterMark in objects, not bytes.
Backpressure from a slow sink slows the file read.
Batch writes to the database, and use pipeline for cleanup.
Common mistakes
Splitting each chunk on newline without keeping the partial last line.
Collecting all rows in an array before processing.
Inserting one database row per await instead of batching.
Decoding bytes to strings chunk by chunk and breaking multi-byte characters.
Follow-ups
How would you add retry and a dead-letter file for bad rows?
How can you process the file in parallel on several CPU cores?
What would you change to resume after a crash at row 50 million?
Tips
Draw the stages and say where each buffer lives.
Mention the multi-byte character trap.
Add batching and checkpointing to show production experience in general terms.
12.nodejs-0012Easyfresher
What is a Buffer in Node.js, and how do encodings like utf8, hex and base64 work with it?
A Buffer is a fixed-size block of raw bytes, and in current Node it is a subclass of Uint8Array. Encodings define how text becomes bytes (Buffer.from(text, encoding)) and how bytes become text (buf.toString(encoding)). Byte length and string length are different for non-ASCII text.
Full answer
JavaScript strings are text. Files, sockets and hashes work with bytes. Buffer is the bridge: a fixed-length sequence of bytes, with methods for reading, writing, slicing and converting.
Since Node 4 a Buffer is a Uint8Array with extra methods, so it works with typed-array APIs and Web APIs.
An encoding is the rule that maps characters to bytes:
utf8 (the default): one to four bytes per character. English letters use one byte, Devanagari letters use three.
hex: two hex digits per byte, often used for hashes.
base64: three bytes become four characters. It is used in data URLs, JWT parts and emails.
latin1 and ascii: one byte per character, for legacy data.
Because of this, string.length counts UTF-16 code units, while Buffer.byteLength(string) counts bytes. They are equal only for plain ASCII.
Buffers are fixed size. You cannot push into them. To combine pieces, use Buffer.concat([a, b]). Compare with Buffer.compare or buf.equals, never with ==.
The Hindi word has 6 UTF-16 code units and takes 18 bytes in UTF-8. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
string length: 6
byte length: 18 (same as Buffer.byteLength: 18)
is a Uint8Array: true
hex: 48656c6c6f205363686f6f6c616265
base64: SGVsbG8gU2Nob29sYWJl
round trip: Hello Schoolabe
equals: true
concat: foobar
Key points
Buffer is raw bytes and a subclass of Uint8Array.
Encodings convert between text and bytes: utf8, hex, base64 and others.
String length and byte length differ for non-ASCII text.
Use Buffer.concat to join and buf.equals to compare.
Common mistakes
Assuming string.length equals the number of bytes.
Comparing buffers with == or ===, which compares references.
Using new Buffer(), which is deprecated and unsafe. Use Buffer.from or Buffer.alloc.
Calling toString() on a partial multi-byte chunk.
Follow-ups
How is Buffer different from ArrayBuffer?
What is base64url and where is it used?
How do you convert a Buffer to JSON?
Tips
Show the byte length vs string length example. It proves you understand encodings.
Say Buffer extends Uint8Array.
Mention that new Buffer() is deprecated.
13.nodejs-0013Mediummid
What is the difference between Buffer.alloc, Buffer.allocUnsafe and Buffer.from, and does subarray copy data?
Buffer.alloc returns zero-filled memory. Buffer.allocUnsafe skips the zero-fill and may contain old data, so it must be fully overwritten before use. Buffer.from copies its input. subarray does not copy: it returns a view over the same memory.
Full answer
Three ways to create a Buffer:
Buffer.alloc(n): n bytes, all set to zero. Safe and a bit slower.
Buffer.allocUnsafe(n): n bytes that were not cleared. They can hold leftovers from earlier use of the memory, such as parts of another request. If you send such a buffer to a client without overwriting every byte, you can leak secrets. Use it only when you will fill the whole buffer immediately, for speed.
Buffer.from(x): creates a Buffer from a string, an array, or another Buffer. From another Buffer or array it copies the data.
Memory pool: small buffers made by allocUnsafe and by Buffer.from(string) (smaller than half of Buffer.poolSize) are cut from a shared pool. The pool was 8 KB for many years and is 64 KB on Node 24. That avoids many tiny allocations, but it means buf.buffer (the underlying ArrayBuffer) is larger than the buffer itself. Never read buf.buffer directly, and if a tiny buffer must live long, use Buffer.allocUnsafeSlow or copy it, so it does not keep the whole pool alive.
buf.subarray(start, end) (and the older buf.slice) returns a new Buffer object that points to the same memory. Changing one changes the other. To get an independent copy, use Buffer.from(buf) or Buffer.copyBytesFrom.
The underlying ArrayBuffer sizes show that a small unsafe buffer lives inside the shared pool (Buffer.poolSize bytes), while alloc gets its own 4 bytes. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
alloc is all zeros: true
alloc underlying ArrayBuffer size: 4
allocUnsafe length: 4 | underlying ArrayBuffer size: 65536
Buffer.poolSize: 65536
after changing the view: Zbcdef
after changing the copy: Zbcdef | copy: Abcdef
Key points
alloc zero-fills. allocUnsafe does not, and can expose old data.
Small buffers from allocUnsafe and Buffer.from(string) come from a shared pool (Buffer.poolSize).
Overwrite every byte of an allocUnsafe buffer before use.
Common mistakes
Using allocUnsafe for performance and sending the result without filling it.
Assuming slice or subarray copies the data.
Reading buf.buffer and expecting only the bytes of that Buffer.
Keeping a tiny pooled buffer for a long time and holding the whole pool in memory.
Follow-ups
Why did Node add the pool?
What is the difference between Buffer.slice and Uint8Array.prototype.slice?
How would you securely clear a buffer holding a secret?
Tips
Name the security risk of allocUnsafe in one sentence.
Say subarray is a view, and give the example that proves it.
Mention zero-fill cost as the only reason to use allocUnsafe.
14.nodejs-0014Hardsenior
How do you read and write binary data with Buffer, and why can toString() on streamed chunks corrupt text?
Buffer has read and write methods for fixed-size integers and floats in big-endian or little-endian order, so you can build and parse binary packets. When text arrives in chunks, a multi-byte UTF-8 character can be cut between chunks, so call StringDecoder (or set a stream encoding) instead of chunk.toString().
Full answer
Binary protocols (file headers, network packets, database drivers) pack numbers into exact byte positions. Buffer offers methods for each size: writeUInt8, writeUInt16BE, writeUInt32LE, writeInt32BE, writeFloatLE, writeDoubleBE and writeBigUInt64BE, with matching read methods.
Endianness is the order of bytes inside a number. Big-endian (BE) puts the most significant byte first, as network protocols do. Little-endian (LE) puts it last, as most CPUs do. The two sides must agree. For a value 0x0102, BE gives bytes 01 02 and LE gives 02 01.
A typical packet design: a magic number, a version byte, a length field, then the payload. The reader checks the magic, reads the length, and waits until it has that many bytes. With streams, one packet may arrive in two chunks, or two packets in one chunk, so the reader must keep a leftover buffer.
Text has a similar problem. UTF-8 characters take one to four bytes. A chunk boundary can fall inside a character. Calling toString() on each chunk then produces replacement characters. Fix it with string_decoder.StringDecoder, which keeps incomplete bytes until the next chunk, or by calling stream.setEncoding('utf8').
Always validate lengths from untrusted input before allocating a buffer, otherwise a client can request a huge allocation.
javascript
const { StringDecoder } = require('node:string_decoder');
// 1. Build and parse a small binary packet: magic(2) | version(1) | id(4, LE) | marks(8, double BE)
const packet = Buffer.alloc(15);
packet.writeUInt16BE(0xcafe, 0);
packet.writeUInt8(1, 2);
packet.writeUInt32LE(70001, 3);
packet.writeDoubleBE(87.5, 7);
console.log('packet hex:', packet.toString('hex'));
console.log('parsed:', {
magic: packet.readUInt16BE(0).toString(16),
version: packet.readUInt8(2),
id: packet.readUInt32LE(3),
marks: packet.readDoubleBE(7),
});
// 2. The same number in the two byte orders.
const two = Buffer.alloc(2);
two.writeUInt16BE(0x0102);
const be = two.toString('hex');
two.writeUInt16LE(0x0102);
console.log('0x0102 as BE:', be, '| as LE:', two.toString('hex'));
// 3. A multi-byte word cut between chunks.
const word = 'नमस्ते';
const bytes = Buffer.from(word);
const chunk1 = bytes.subarray(0, 4);
const chunk2 = bytes.subarray(4);
const naive = chunk1.toString() + chunk2.toString();
const decoder = new StringDecoder('utf8');
const safe = decoder.write(chunk1) + decoder.write(chunk2) + decoder.end();
console.log('naive toString matches original:', naive === word);
console.log('StringDecoder matches original: ', safe === word);
The packet layout is made up for the example. Part 3 cuts the 18 bytes of a Hindi word at byte 4, in the middle of the second letter. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
packet hex: cafe01711101004055e00000000000
parsed: { magic: 'cafe', version: 1, id: 70001, marks: 87.5 }
0x0102 as BE: 0102 | as LE: 0201
naive toString matches original: false
StringDecoder matches original: true
Key points
Use read/write methods with an explicit endianness.
Network byte order is big-endian.
Length-prefixed packets need a leftover buffer for partial data.
StringDecoder or setEncoding prevents broken multi-byte characters.
Validate length fields from untrusted data.
Common mistakes
Mixing up big-endian and little-endian when two systems talk.
Calling chunk.toString() on every stream chunk of text.
Trusting a length field and allocating a buffer of that size.
Assuming one data event equals one whole message.
Follow-ups
How do you frame messages on a TCP stream?
When would you use DataView instead of Buffer methods?
How do you handle 64-bit integers safely in JavaScript?
Tips
Draw the packet layout with offsets before writing code.
Link the chunk problem to a real one: text files read in 64 KB pieces.
Mention length limits as a security check.
15.nodejs-0015Easyfresher
What are the three styles of the fs API (callback, sync, promises), and which should you use?
fs offers callback functions, synchronous functions ending in Sync, and promise functions in fs/promises. Use the promise API in application code, the Sync versions only at start-up or in scripts, and keep callbacks for old code. File errors carry a code such as ENOENT that you can check.
Full answer
Every common file operation exists in three forms:
Callback: fs.readFile(path, cb). The original style. The callback receives (err, data).
Synchronous: fs.readFileSync(path). Blocks the event loop until the work is done and throws on error.
Promise: require('node:fs/promises').readFile(path). Returns a promise, works with await and try/catch.
Pick the promise API by default. It is clean to write, keeps the event loop free, and fits async functions. Use Sync functions when blocking is harmless: reading a config file at start-up, in a CLI tool, or in a build script. Never use them inside a request handler.
Errors are Error objects with a code property. Common ones: ENOENT (no such file or directory), EACCES (permission denied), EEXIST (already exists), EISDIR (is a directory), ENOTEMPTY (directory not empty), EMFILE (too many open files). Check err.code, not the message text, because messages can change.
Always pass an encoding ('utf8') to get a string. Without it you get a Buffer. Paths are relative to the current working directory of the process, not to the file, so build absolute paths with path.join(__dirname, ...) when it matters.
The snippet works in a temporary folder and removes it at the end. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
promise read: "present: 28\nabsent: 2\n"
sync size: 22 bytes
callback lines: 2
error code: ENOENT
Key points
Three styles: callback, Sync, and promises (fs/promises).
Promise API is the default choice. Sync only when blocking is acceptable.
Check error.code values such as ENOENT.
Without an encoding you get a Buffer.
Common mistakes
Using readFileSync inside an HTTP request handler.
Matching error messages instead of err.code.
Using a relative path and getting ENOENT because the working directory is different.
Forgetting the encoding and being surprised by a Buffer.
Follow-ups
How do you read a JSON file safely?
What does EMFILE mean and how do you avoid it?
Why can fs.promises.readFile still block the thread pool?
Tips
State a clear rule for when Sync is fine.
Mention ENOENT by name.
Show the same operation in two styles to prove you know both.
16.nodejs-0016Easyfresher
What is the difference between path.join, path.resolve and path.normalize, and why use the path module at all?
path.join glues segments with the platform separator and cleans the result. path.resolve builds an absolute path from right to left, using the current directory if needed, and an absolute segment resets the path. path.normalize only cleans one path. The module hides differences such as / on Linux and \ on Windows.
Full answer
Building paths with string concatenation breaks across platforms. Linux and macOS use /, Windows uses . The path module uses the right separator, and handles ., .. and doubled separators.
path.join(a, b, ...): joins the parts and normalizes. Leading slashes of later parts do not reset the path: join('/srv', '/etc') gives /srv/etc. The result can be relative.
path.resolve(a, b, ...): processes from right to left until it has an absolute path. If it never gets one, it prepends process.cwd(). A later absolute segment wins: resolve('/srv', '/etc') gives /etc. The result is always absolute.
path.normalize(p): removes redundant separators and resolves . and .. segments in one path.
Other helpers: basename, dirname, extname, parse, format, relative, isAbsolute.
path.posix and path.win32 give the two styles on any machine. They are useful in tests, and when you must produce a path for another operating system.
Security note: join and resolve do not make a path safe. A user value like ../../etc/passwd still escapes the base folder. Check the result against the base, as shown in the path traversal question.
javascript
const path = require('node:path');
// Using the posix flavour so the output is the same on every machine.
const p = path.posix;
console.log(p.join('/srv', 'app', '../logs', 'today.txt'));
console.log(p.join('/srv', '/etc'));
console.log(p.resolve('/srv', 'app', '../logs', 'today.txt'));
console.log(p.resolve('/srv', '/etc'));
console.log(p.normalize('/srv//app/./data/../file.txt'));
console.log(p.basename('/reports/term1/marks.csv'));
console.log(p.basename('/reports/term1/marks.csv', '.csv'));
console.log(p.extname('/reports/term1/marks.csv'));
console.log(p.relative('/reports/term1', '/reports/term2/marks.csv'));
console.log(p.parse('/reports/term1/marks.csv'));
// The Windows flavour on the same machine.
console.log(path.win32.join('C:\\data', '..', 'backup', 'marks.csv'));
console.log(path.win32.basename('C:\\data\\marks.csv'));
The posix and win32 objects make the output identical on any operating system. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
/srv/logs/today.txt
/srv/etc
/srv/logs/today.txt
/etc
/srv/app/file.txt
marks.csv
marks
.csv
../term2/marks.csv
{
root: '/',
dir: '/reports/term1',
base: 'marks.csv',
ext: '.csv',
name: 'marks'
}
C:\backup\marks.csv
marks.csv
Key points
join concatenates and normalizes. resolve returns an absolute path.
A later absolute segment resets resolve but not join.
path.posix and path.win32 allow both styles on one machine.
Path helpers do not protect against path traversal.
Common mistakes
Concatenating paths with + '/' + .
Assuming join and resolve give the same result.
Forgetting that resolve depends on the current working directory for relative input.
Trusting a joined user path without checking that it stays inside the base folder.
Follow-ups
How do you get the directory of the current file in ESM?
What does path.relative return?
Why is path.join(__dirname, 'x') safer than 'x' alone?
Tips
Use the 'right to left' phrase for resolve.
Demonstrate the join('/srv', '/etc') trap.
Link to security: normalised paths still need a base check.
17.nodejs-0017Mediummid
How do you check whether a file exists in Node.js, and why is 'check then use' a problem?
fs.exists is deprecated. fs.access or fs.stat tell you whether a file exists right now, but another process can create or delete it before your next step. The safe pattern is to act and handle the error, for example open with flag 'wx' to create a file only if it does not exist.
Full answer
Checking first and acting later is a time-of-check to time-of-use (TOCTOU) bug. Between "the file is not there" and "write the file", another process or another request can create it, and you overwrite its data. The same race exists for "the file is there, so read it", when someone deletes it in between.
Options:
fs.promises.access(path) resolves if the file is accessible and rejects with ENOENT otherwise. Fine for a quick check where a race does not matter, such as showing a message.
fs.promises.stat(path) also gives size and type.
fs.existsSync(path) is still supported and returns a boolean, but the same race applies. fs.exists (callback) is deprecated.
Do the real operation and handle the error. Open with the flag 'wx' to fail with EEXIST if the file already exists, 'r' to fail with ENOENT if it does not. The check and the action then happen in one atomic step in the operating system.
For "create the directory if needed", use fs.mkdir(path, { recursive: true }). It succeeds if the directory already exists. For "delete if present", use fs.rm(path, { force: true }), which ignores a missing file.
Lock files, atomic rename (write a temp file, then rename it over the target) and database transactions are the next tools when many processes share files.
javascript
const fsp = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
async function main() {
const dir = await fsp.mkdtemp(path.join(os.tmpdir(), 'lock-'));
const lock = path.join(dir, 'job.lock');
// Race-free "create only if missing": the OS decides who wins.
const first = await fsp.open(lock, 'wx');
await first.close();
console.log('first process got the lock');
try {
await fsp.open(lock, 'wx');
} catch (err) {
console.log('second process failed with:', err.code);
}
// Idempotent helpers: safe to call twice.
await fsp.mkdir(path.join(dir, 'a', 'b'), { recursive: true });
await fsp.mkdir(path.join(dir, 'a', 'b'), { recursive: true });
await fsp.rm(path.join(dir, 'does-not-exist'), { force: true });
console.log('mkdir recursive and rm force did not throw');
// A plain check works, but it can be stale a moment later.
const exists = await fsp.access(lock).then(() => true, () => false);
console.log('lock exists right now:', exists);
await fsp.rm(dir, { recursive: true });
}
main();
The 'wx' flag means write, and fail if the path exists. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
first process got the lock
second process failed with: EEXIST
mkdir recursive and rm force did not throw
lock exists right now: true
Key points
Check then act is a race condition (TOCTOU).
Use flags such as 'wx' to make the check part of the operation.
mkdir with recursive and rm with force are idempotent.
fs.exists is deprecated.
Common mistakes
Calling existsSync and then writeFileSync as if it were atomic.
Using the deprecated fs.exists.
Swallowing every error instead of checking for ENOENT.
Writing directly over a config file instead of writing a temp file and renaming it.
Follow-ups
How do you replace a file atomically?
How would two Node processes share a lock?
What does the 'ax' flag do?
Tips
Use the words 'race condition' and give the scenario.
Show the 'wx' flag, because it proves you know the safe pattern.
Mention rename for atomic updates as the next idea.
18.nodejs-0018Easyfresher
What can you learn from the os and process modules, and how do you use them to size a worker pool?
The os module reports facts about the machine: CPU count, memory, platform, home and temp folders, line ending. The process object reports facts about the running program: pid, arguments, environment, versions, memory use. os.availableParallelism() is the usual starting number for a worker pool.
Full answer
os module, about the machine:
os.availableParallelism(): how many tasks can run in parallel (added in Node 18.14 and 19.4). Prefer it over os.cpus().length, which counts logical CPUs even when a container is limited.
Container warning: inside Docker or Kubernetes, os.totalmem() may show the host's memory, not your limit. Read cgroup limits or process.constrainedMemory() when sizing caches.
For a worker pool, start with os.availableParallelism() for CPU-bound jobs, and a larger number for jobs that mostly wait on I/O. Then measure.
javascript
const os = require('node:os');
console.log('availableParallelism is a positive integer:', Number.isInteger(os.availableParallelism()) && os.availableParallelism() > 0);
console.log('total memory is more than free memory:', os.totalmem() > os.freemem());
console.log('platform is a string:', typeof os.platform());
console.log('EOL is a line break:', os.EOL === '\n' || os.EOL === '\r\n');
console.log('tmpdir is absolute:', require('node:path').isAbsolute(os.tmpdir()));
process.env.PASS_MARK = 40;
console.log('env value type:', typeof process.env.PASS_MARK, JSON.stringify(process.env.PASS_MARK));
console.log('argv length (node path + script path):', process.argv.length);
console.log('Node major version is a number:', Number.isInteger(Number(process.versions.node.split('.')[0])));
const { rss, heapUsed } = process.memoryUsage();
console.log('rss is larger than heapUsed:', rss > heapUsed);
The snippet prints checks instead of raw values, because the real values differ between machines. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
availableParallelism is a positive integer: true
total memory is more than free memory: true
platform is a string: string
EOL is a line break: true
tmpdir is absolute: true
env value type: string "40"
argv length (node path + script path): 2
Node major version is a number: true
rss is larger than heapUsed: true
Key points
os describes the machine. process describes the running program.
Use os.availableParallelism() to size pools.
process.env values are always strings.
Container limits may differ from what os reports.
Common mistakes
Assuming process.env.PORT is a number.
Using os.cpus().length in a container with a CPU limit.
Trusting os.totalmem() as the memory limit of a container.
Putting secrets in process.argv, where other users can see them with ps.
Follow-ups
How do you pass the port number from the command line?
What does rss mean compared with heapUsed?
How would you detect that Node runs inside a container?
Tips
Mention the string-only rule of process.env.
Name availableParallelism, because older answers say os.cpus().length.
Add the container caveat to show production awareness.
19.nodejs-0019Easyfresher
What are the main differences between CommonJS (require) and ES modules (import) in Node.js?
CommonJS loads files synchronously with require and module.exports. ES modules use import and export, are loaded asynchronously, are always in strict mode, support top-level await and have live bindings. Node decides the type from the file extension (.cjs, .mjs) or the nearest package.json type field.
Full answer
CommonJS (CJS) is the original Node module system:
require('x') runs the file at that moment and returns module.exports. It is synchronous and can be called anywhere, even inside an if.
It gives you __filename, __dirname, require, module and exports in each file.
What you get is whatever module.exports held when require returned. If the module later reassigns its own variable, importers do not see the change.
ES modules (ESM) are the standard JavaScript system:
import and export are static. They are analysed before the code runs, which allows tree shaking and early errors.
Loading is asynchronous, and top-level await is allowed.
Code is always in strict mode. There is no __dirname or require. Use import.meta.url, import.meta.dirname and createRequire.
Imports are live bindings. If the exporting module changes its exported variable, importers see the new value.
File extensions are required in relative imports ('./util.js').
How Node picks the type: .mjs is ESM, .cjs is CJS, and .js follows the "type" field in the nearest package.json ("module" or "commonjs", default commonjs).
Interop: ESM can import CJS (the default import is module.exports). CJS can load ESM with dynamic import(), and since Node 22.12 also with require() when the ESM graph has no top-level await.
javascript
// Save as app.mjs: the .mjs extension makes this file an ES module.
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
console.log('require defined:', typeof require);
console.log('__dirname defined:', typeof __dirname);
console.log('import.meta.url starts with file://:', import.meta.url.startsWith('file://'));
// Create a small CommonJS file and import it from this ES module.
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'esm-'));
const cjsFile = path.join(dir, 'grades.cjs');
fs.writeFileSync(cjsFile, "module.exports = { pass: (m) => m >= 40 };\n");
const grades = await import(pathToFileURL(cjsFile).href); // top-level await
console.log('default export is module.exports:', typeof grades.default.pass);
console.log('pass(39):', grades.default.pass(39), '| pass(40):', grades.default.pass(40));
fs.rmSync(dir, { recursive: true });
This file uses the .mjs extension. Top-level await and import.meta only work in ES modules. Save it as app.mjs and run it with node app.mjs.
Output (Node.js v24.22.1, same on two runs):
require defined: undefined
__dirname defined: undefined
import.meta.url starts with file://: true
default export is module.exports: function
pass(39): false | pass(40): true
ESM has top-level await, strict mode and live bindings.
The type field and the extension decide the module type.
ESM has no __dirname or require.
Common mistakes
Calling require() in a .mjs file.
Leaving out the file extension in a relative ESM import.
Setting type module in package.json and forgetting to rename old .js CommonJS files to .cjs.
Believing import is just a different spelling of require.
Follow-ups
What is a live binding?
How do you import a JSON file in ESM?
What happens when a CJS file calls require on an ESM file?
Tips
Name the three things Node checks to pick the module type.
State that ESM is the standard and CJS is the legacy default.
Mention top-level await as a practical difference.
20.nodejs-0020Mediummid
How does require caching work in CommonJS, and what happens with circular dependencies?
The first require of a file runs it and stores module.exports in require.cache. Later requires return the cached object without running the file again. With a circular dependency, the second file receives the partially filled exports of the first file, which can be an empty object.
Full answer
When Node loads a file with require, it resolves the full path, checks require.cache (keyed by that path), and returns the cached exports if present. If not, it creates a module object, adds it to the cache before running the code, runs the file, and returns module.exports.
Caching has two effects:
A module is a singleton per resolved path. A file with top-level state (a counter, a database pool) shares that state with every file that requires it.
Top-level code runs once. Requiring the same file twice prints its console.log once.
Because the module is added to the cache before it finishes running, circular dependencies do not loop forever. If a.js requires b.js, and b.js requires a.js at the top, b.js gets the exports object of a.js as it is at that moment. If a.js has not yet assigned its exports, b.js sees an empty object. Functions added to exports later become visible on the same object, but replacing the object with module.exports = {...} later does not reach b.js.
Fixes: avoid the cycle by moving shared code to a third module, require lazily inside the function that needs it, or add to exports (exports.x = ...) before requiring the other file.
Deleting a key from require.cache forces a reload. That is used by some test tools and is not safe for application code.
javascript
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cjs-'));
const write = (name, text) => fs.writeFileSync(path.join(dir, name), text);
write('a.js', `
console.log('a starts');
exports.early = 'set before requiring b';
const b = require('./b.js');
console.log('a sees from b:', b.fromA);
exports.late = 'set after requiring b';
console.log('a ends');
`);
write('b.js', `
console.log('b starts');
const a = require('./a.js'); // a is only partly loaded here
console.log('b sees from a:', Object.keys(a));
exports.fromA = a.early;
console.log('b ends');
`);
require(path.join(dir, 'a.js'));
require(path.join(dir, 'a.js')); // second call: nothing runs, cache is used
console.log('files in cache:', Object.keys(require.cache).filter((f) => f.startsWith(dir)).length);
fs.rmSync(dir, { recursive: true });
b.js sees only the early property of a.js, because a.js is still in the middle of loading. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
a starts
b starts
b sees from a: [ 'early' ]
b ends
a sees from b: set before requiring b
a ends
files in cache: 2
Key points
Modules are cached by resolved path and run once.
The cache gives singleton behaviour.
A cycle gives the second module a partial exports object.
Best fix: remove the cycle by extracting shared code.
Common mistakes
Thinking require runs the file again each time.
Replacing module.exports after another file has already required the module in a cycle.
Hiding a cycle with try/catch.
Keeping mutable global state in a module and expecting a fresh copy per require.
Follow-ups
How would you reset a module between two tests?
Does ESM handle cycles differently?
Where does the cache key come from when the same package is installed twice?
Tips
Walk through the sequence of logs in the snippet out loud.
Explain that the module is cached before it finishes running.