Node.js interview questions: answers with real output
The back-end JavaScript questions on the event loop, modules, streams and errors, answered in plain words with code that was actually run.
Node.js interviews focus on how the event loop schedules work (synchronous code, then nextTick, then promises, then timers and setImmediate), how require caches modules, EventEmitter and its 'error' event, streams and pipeline, error handling with async/await, and when worker threads help. Below are 14 questions; every example was run in Node.js and shows its real output.
Basic node.js interview questions
Basic1. Is Node.js single-threaded?
Your JavaScript runs on one main thread, but I/O does not wait on it. Network I/O is non-blocking and is handled by the event loop itself, using the operating system's asynchronous mechanisms, while file system calls (and dns.lookup) run on libuv's thread pool, the Worker Pool; when a result is ready, Node.js runs your callback on the main thread. That is why a slow loop blocks everything while slow I/O does not.
JavaScriptconst fs = require('fs');
console.log('1 start');
fs.readFile(__filename, () => console.log('3 file read finished'));
let x = 0; for (let i = 0; i < 1e6; i++) x += i;
console.log('2 loop finished first, total', x);Output (Node.js 24.15.0)1 start 2 loop finished first, total 499999500000 3 file read finished
Checked against: Node.js guide: Don't block the event loop (or the Worker Pool), Node.js docs: the event loop, timers and nextTick
Basic2. What is the difference between module.exports and exports?
exports starts as a reference to module.exports. Adding properties to either works, but assigning a new object to exports breaks the link, and require() always returns module.exports.
JavaScriptconst Module = require('module');
const m = new Module('demo');
m._compile("exports.a = 1; exports = { b: 2 }; module.exports.c = 3;", 'demo.js');
console.log(m.exports);Output (Node.js 24.15.0){ a: 1, c: 3 }Basic3. Why does require() return the same object twice?
Modules are cached after the first load, so every require() of the same file returns the same exports object and the module's top-level code runs only once. That is how a module can act as a shared singleton.
JavaScriptconst fs = require('fs'), os = require('os'), path = require('path');
const file = path.join(os.tmpdir(), 'ti46-counter.js');
fs.writeFileSync(file, "console.log('module body runs'); module.exports = { hits: 0 };");
const a = require(file); a.hits++;
const b = require(file);
console.log('same object:', a === b, 'hits:', b.hits);
fs.unlinkSync(file);Output (Node.js 24.15.0)module body runs same object: true hits: 1
Basic4. How do you convert between strings, Buffers, hex and base64?
A Buffer holds raw bytes. Buffer.from(string) encodes text as UTF-8 by default, and toString('hex') or toString('base64') decodes it back in another format. Note that byte length and character length differ for non-ASCII text.
JavaScriptconst b = Buffer.from('café');
console.log(b.length, 'bytes for', 'café'.length, 'characters');
console.log(b.toString('hex'));
console.log(b.toString('base64'));
console.log(Buffer.from('Y2Fmw6k=', 'base64').toString());Output (Node.js 24.15.0)5 bytes for 4 characters 636166c3a9 Y2Fmw6k= café
Basic5. How do you handle errors with async/await?
Wrap awaited calls in try/catch. A rejected promise that nobody catches becomes an unhandled rejection, so decide where each error should be caught and handle it there.
JavaScriptconst fetchJob = id => id > 0 ? Promise.resolve({ id, title: 'Analyst' }) : Promise.reject(new Error('bad id ' + id));
(async () => {
try {
console.log(await fetchJob(7));
await fetchJob(-1);
} catch (err) {
console.log('caught:', err.message);
}
})();Output (Node.js 24.15.0){ id: 7, title: 'Analyst' }
caught: bad id -1Intermediate node.js interview questions
Intermediate6. In what order do nextTick, promises, setImmediate and setTimeout run?
Synchronous code runs first. Then the nextTick queue empties, then the promise microtask queue. Inside an I/O callback, setImmediate always runs before a setTimeout of 0; in the main module that pair has no fixed order, which is why this example starts inside fs.readFile.
JavaScriptconst fs = require('fs');
fs.readFile(__filename, () => {
setTimeout(() => console.log('5 setTimeout'), 0);
setImmediate(() => console.log('4 setImmediate'));
Promise.resolve().then(() => console.log('3 promise'));
process.nextTick(() => console.log('2 nextTick'));
console.log('1 sync');
});Output (Node.js 24.15.0)1 sync 2 nextTick 3 promise 4 setImmediate 5 setTimeout
Checked against: Node.js docs: the event loop, timers and nextTick
Intermediate7. What is an EventEmitter and how does once() differ from on()?
EventEmitter lets an object emit named events that listeners subscribe to. on() keeps listening; once() removes itself after the first call. Listeners run synchronously, in the order they were added.
JavaScriptconst { EventEmitter } = require('events');
const jobs = new EventEmitter();
jobs.on('posted', t => console.log('on:', t));
jobs.once('posted', t => console.log('once:', t));
jobs.emit('posted', 'Data Analyst');
jobs.emit('posted', 'QA Engineer');
console.log('listeners left:', jobs.listenerCount('posted'));Output (Node.js 24.15.0)on: Data Analyst once: Data Analyst on: QA Engineer listeners left: 1
Checked against: Node.js API: events
Intermediate8. What happens when an EventEmitter emits 'error' with no listener?
The error is thrown and, if nothing catches it, the process crashes. Always attach an 'error' listener to emitters and streams you create.
JavaScriptconst { EventEmitter } = require('events');
const e = new EventEmitter();
try { e.emit('error', new Error('disk full')); } catch (err) { console.log('thrown:', err.message); }
e.on('error', err => console.log('handled:', err.message));
e.emit('error', new Error('disk full'));Output (Node.js 24.15.0)thrown: disk full handled: disk full
Checked against: Node.js API: events
Intermediate9. What are streams and why use them?
Streams process data in chunks instead of loading everything into memory. The four types are Readable, Writable, Duplex and Transform; pipeline() connects them and passes errors and cleanup through the whole chain.
JavaScriptconst { Readable, Transform, Writable, pipeline } = require('stream');
const upper = new Transform({ transform(chunk, enc, cb) { cb(null, chunk.toString().toUpperCase()); } });
const out = [];
const sink = new Writable({ write(chunk, enc, cb) { out.push(chunk.toString()); cb(); } });
pipeline(Readable.from(['resume ', 'cover letter ', 'interview']), upper, sink, err => {
console.log(err ? 'failed' : 'done:', out.join(''));
});Output (Node.js 24.15.0)done: RESUME COVER LETTER INTERVIEW
Checked against: Node.js API: stream
Intermediate10. How do you turn a callback API into a promise?
util.promisify wraps a function that takes a Node-style callback (err, value) and returns a version that returns a promise. Many core modules also ship promise versions, such as fs/promises.
JavaScriptconst { promisify } = require('util');
function lookup(id, cb) { setImmediate(() => id ? cb(null, 'job ' + id) : cb(new Error('missing id'))); }
const lookupAsync = promisify(lookup);
lookupAsync(12).then(console.log);
lookupAsync(0).catch(e => console.log('error:', e.message));Output (Node.js 24.15.0)job 12 error: missing id
Advanced node.js interview questions
Advanced11. What is backpressure in Node.js streams, and how do you handle it?
When a writable stream's buffer reaches its highWaterMark, write() returns false. The producer should stop writing and wait for the 'drain' event before writing again; pipe() and stream.pipeline() do this for you. Ignoring the signal makes Node buffer everything in memory.
JavaScriptconst { Writable } = require('stream');
const slow = new Writable({ highWaterMark: 4, write(chunk, enc, cb) { setImmediate(cb); } });
let i = 0;
function writeMore() {
while (i < 6) {
const ok = slow.write('ab');
console.log('write', i, 'buffered', slow.writableLength, 'returned', ok);
i++;
if (!ok) { slow.once('drain', () => { console.log('drain: buffer emptied, resuming'); writeMore(); }); return; }
}
slow.end(() => console.log('finished'));
}
writeMore();Output (Node.js 24.15.0)write 0 buffered 2 returned true write 1 buffered 4 returned false drain: buffer emptied, resuming write 2 buffered 2 returned true write 3 buffered 4 returned false drain: buffer emptied, resuming write 4 buffered 2 returned true write 5 buffered 4 returned false drain: buffer emptied, resuming finished
Checked against: Node.js API: stream
Advanced12. When would you use worker threads?
For CPU-heavy JavaScript such as parsing or hashing large inputs, which would otherwise block the event loop. They are not needed for I/O, which Node.js already handles asynchronously, and unlike child processes they can share memory.
JavaScriptconst { Worker } = require('worker_threads');
const w = new Worker("const { parentPort, workerData } = require('worker_threads'); let s = 0; for (let i = 1; i <= workerData; i++) s += i; parentPort.postMessage(s);", { eval: true, workerData: 1000000 });
w.on('message', sum => console.log('sum from worker:', sum));
w.on('exit', code => console.log('worker exit code', code));Output (Node.js 24.15.0)sum from worker: 500000500000 worker exit code 0
Checked against: Node.js API: worker_threads
Advanced13. How do you read and write files without blocking?
Use the promise API in fs/promises (or the callback versions). The Sync methods block the event loop and are fine only in startup scripts or CLIs.
JavaScriptconst fs = require('fs/promises'), os = require('os'), path = require('path');
(async () => {
const f = path.join(os.tmpdir(), 'ti46-notes.txt');
await fs.writeFile(f, 'line one\n');
await fs.appendFile(f, 'line two\n');
console.log((await fs.readFile(f, 'utf8')).trim().split('\n'));
await fs.unlink(f);
})();Output (Node.js 24.15.0)[ 'line one', 'line two' ]
Advanced14. Why should you not block the event loop, and how can you spot it?
While a synchronous task runs, no other callback can run, so timers fire late and requests queue up. Measuring how late a timer fires is a simple way to see it.
JavaScriptconst start = Date.now();
setTimeout(() => console.log('timer late by at least 200 ms:', Date.now() - start >= 250), 50);
const until = Date.now() + 250; while (Date.now() < until) {}Output (Node.js 24.15.0)timer late by at least 200 ms: true
How to practice with this page
- Predict each example's output before reading it, then check.
- Explain why the order is what it is: that is the usual follow-up question.
- Run the examples with node -e and change one line at a time.
- Back-end roles: practice an Express or Fastify route and a database call as well.
Related interview prep and tools
Scope, closures and the event loop basics.
Open →QuestionsREST API interview questionsMethods, status codes and idempotency, with real responses.
Open →QuestionsReact interview questionsFront-end questions for full-stack roles.
Open →RoleWeb developer interview questionsRole-specific questions.
Open →Free toolResume summary generatorDraft a summary for a Backend Developer role; the title is filled in, you add your experience.
Open →Free toolLinkedIn headline generatorWrite a headline for a Backend Developer search.
Open →Disclosure: TryHired makes HIRED, a paid job-search program, so we have a conflict of interest when we mention it. This question bank is free, with no TryHired signup.
Questions people ask
What Node.js topics come up often in interviews?
Should I learn CommonJS or ES modules for a Node.js interview?
Is Express part of Node.js?
How this page is built
TryHired wrote these questions and answers. Every code block on this page was executed with Node.js 24.15.0 when the page was built (2026-11-15), and the output shown is the real output; the build stops if any example fails. The question list is general practice: it does not predict what a particular employer will ask.
- Interviewers ask different questions for different roles and levels.
- Answers are short explanations, not complete references.
- Examples ran in Node.js on the build machine using CommonJS modules. Under ES modules (import/export), module.exports and exports, require.cache and __filename work differently: ES modules use export, the module cache is not exposed as require.cache, and import.meta.url replaces __filename.
- Node.js guide: Don't block the event loop (or the Worker Pool) (read 2026-11-15)
- Node.js docs: the event loop, timers and nextTick (read 2026-11-15)
- Node.js API: events (read 2026-11-15)
- Node.js API: stream (read 2026-11-15)
- Node.js API: worker_threads (read 2026-11-15)