Common pitfalls
suggest changeMost Node.js bugs fall into a small number of patterns. Many come from asynchronous code. Some come from the single-threaded event loop. The rest are Node-specific details that catch people who come from other platforms.
This article shows each pitfall in a short program, the wrong output it produces, and the fix. All examples are ES modules (.mjs files or "type": "module" in package.json) and were run on Node.js 24.
Forgetting await
Calling an async function without await gives you a Promise, not the value:
async function getUser(id) {
if (id <= 0) throw new Error(`invalid id ${id}`);
return { id, name: 'Alice' };
}
const user = getUser(1); // forgot await
console.log(user);
console.log(user.name);
try {
getUser(-1); // forgot await: try/catch can't see the rejection
} catch (err) {
console.log('caught:', err.message); // never runs
}
Promise { { id: 1, name: 'Alice' } }
undefined
file:///app/p01.mjs:2
if (id <= 0) throw new Error(`invalid id ${id}`);
^
Error: invalid id -1
at getUser (file:///app/p01.mjs:2:22)
at file:///app/p01.mjs:11:3
There are two bugs here:
user.nameisundefinedbecauseuseris aPromise. Nothing throws, so the bug can travel far before something breaks.try/catchonly catches errors thrown synchronously. Anasyncfunction never throws synchronously. It returns a rejected promise, and nobody handles it, so the process crashes.
The fix is to add await:
const user = await getUser(1);
console.log(user.name);
try {
await getUser(-1);
} catch (err) {
console.log('caught:', err.message);
}
Alice
caught: invalid id -1
Linters catch this. Turn on @typescript-eslint/no-floating-promises (it needs type information) or at least ESLint's require-await and no-async-promise-executor.
async callbacks in forEach
Array.prototype.forEach ignores the return value of its callback. If the callback is async, the returned promises are thrown away and forEach returns at once:
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function save(item) {
await sleep(10);
console.log('saved', item);
}
const items = ['a', 'b', 'c'];
items.forEach(async (item) => {
await save(item);
});
console.log('all done?');
all done?
saved a
saved b
saved c
"all done?" is printed before anything is saved. Any error thrown by save() becomes an unhandled rejection. The same applies to map, filter and reduce with async callbacks unless you await the result.
Use for...of to run one at a time, or Promise.all to run them all at once:
// sequential: one after another
for (const item of items) {
await save(item);
}
console.log('sequential done');
// concurrent: all at once, wait for all
await Promise.all(items.map((item) => save(item)));
console.log('concurrent done');
saved a
saved b
saved c
sequential done
saved a
saved b
saved c
concurrent done
Awaiting independent operations one by one
The opposite mistake: await in sequence for things that don't depend on each other. Each await waits for the previous one to finish:
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const fetchUser = async () => { await sleep(200); return { name: 'Alice' }; };
const fetchOrders = async () => { await sleep(200); return [1, 2, 3]; };
let start = performance.now();
const user = await fetchUser();
const orders = await fetchOrders();
console.log(`sequential: ${Math.round(performance.now() - start)} ms`);
start = performance.now();
const [user2, orders2] = await Promise.all([fetchUser(), fetchOrders()]);
console.log(`parallel: ${Math.round(performance.now() - start)} ms`);
sequential: 410 ms
parallel: 215 ms
Start all independent operations first and then wait for all of them with Promise.all.
Don't go too far the other way. Promise.all over 10,000 items opens 10,000 database connections or HTTP requests at once. For large lists, process items in batches or use a concurrency limiter such as the p-limit package.
Promise.all fails fast
Promise.all rejects as soon as one promise rejects. You lose the results of the ones that succeeded:
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function fetchPrice(symbol) {
await sleep(10);
if (symbol === 'XYZ') throw new Error(`unknown symbol ${symbol}`);
return { symbol, price: 100 };
}
const symbols = ['AAPL', 'XYZ', 'MSFT'];
try {
const prices = await Promise.all(symbols.map(fetchPrice));
console.log(prices);
} catch (err) {
console.log('Promise.all failed:', err.message);
}
const results = await Promise.allSettled(symbols.map(fetchPrice));
for (const r of results) {
if (r.status === 'fulfilled') console.log('ok ', r.value.symbol);
else console.log('fail', r.reason.message);
}
Promise.all failed: unknown symbol XYZ
ok AAPL
fail unknown symbol XYZ
ok MSFT
Use Promise.all when you need all results or none. Use Promise.allSettled when partial results are useful.
Also note that Promise.all doesn't cancel the other operations. They keep running after the rejection. To really stop them, pass an AbortSignal (see AbortSignal and timeouts).
Unhandled promise rejections crash the process
Since Node.js 15, an unhandled rejection terminates the process, just like an uncaught exception:
async function loadConfig() {
throw new Error('config file missing');
}
loadConfig(); // nobody handles the rejection
setTimeout(() => console.log('still running?'), 100);
file:///app/p05.mjs:2
throw new Error('config file missing');
^
Error: config file missing
at loadConfig (file:///app/p05.mjs:2:9)
at file:///app/p05.mjs:5:1
Node.js v24.20.0
"still running?" is never printed. Every promise must end in an await inside try/catch or in a .catch().
An unhandledRejection handler is useful as a last-resort logger, but it is not a substitute for handling errors where they happen:
async function loadConfig() {
throw new Error('config file missing');
}
process.on('unhandledRejection', (reason) => {
console.error('BUG: unhandled rejection:', reason.message);
process.exitCode = 1;
});
loadConfig().catch((err) => {
console.log('using defaults because:', err.message);
});
loadConfig(); // still forgotten
using defaults because: config file missing
BUG: unhandled rejection: config file missing
More in Unhandled Exception Management and Async error handling.
try/catch around callbacks
try/catch can't catch an error thrown in a callback that runs later, because by then the try block has already finished:
try {
setTimeout(() => {
throw new Error('boom');
}, 10);
} catch (err) {
console.log('caught:', err.message); // never runs
}
file:///app/p06.mjs:3
throw new Error('boom');
^
Error: boom
at Timeout._onTimeout (file:///app/p06.mjs:3:11)
at listOnTimeout (node:internal/timers:685:17)
at process.processTimers (node:internal/timers:618:7)
Node.js v24.20.0
The same is true for callbacks of fs.readFile, http.get, event listeners and so on. Put the try/catch inside the callback, or better, use the promise version of the API (node:fs/promises, node:timers/promises) together with await.
Calling a callback twice
In callback-style code, a forgotten return after reporting an error lets the function continue:
import { readFile } from 'node:fs';
function readJson(path, callback) {
readFile(path, 'utf8', (err, text) => {
if (err) {
callback(err); // missing return!
}
callback(null, JSON.parse(text));
});
}
readJson('missing.json', (err, data) => {
console.log('callback called, err:', err?.code, 'data:', data);
});
callback called, err: ENOENT data: undefined
<anonymous_script>:1
undefined
^
SyntaxError: "undefined" is not valid JSON
at JSON.parse (<anonymous>)
at ReadFileContext.callback (file:///app/p07.mjs:8:25)
The callback runs once with the error, then the code goes on to parse undefined and crashes. In a web server, this kind of bug shows up as Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client, because a response is sent twice.
Always write return callback(err);. Better yet, use promises, where a function can only resolve or reject once:
import { readFile } from 'node:fs/promises';
async function readJson(path) {
const text = await readFile(path, 'utf8');
return JSON.parse(text);
}
try {
await readJson('missing.json');
} catch (err) {
console.log('failed once:', err.code);
}
failed once: ENOENT
See Callback to promise for converting old callback APIs.
Blocking the event loop
Node.js runs your JavaScript on a single thread. While a function runs, nothing else does: no other requests, no timers, no I/O callbacks. A synchronous CPU-heavy call stalls the whole server:
import { pbkdf2Sync } from 'node:crypto';
const start = performance.now();
setTimeout(() => {
console.log(`timer fired after ${Math.round(performance.now() - start)} ms (wanted 10)`);
}, 10);
// simulate a request handler doing CPU-heavy synchronous work
pbkdf2Sync('password', 'salt', 1_000_000, 64, 'sha512');
console.log(`sync work took ${Math.round(performance.now() - start)} ms`);
sync work took 570 ms
timer fired after 572 ms (wanted 10)
The 10 ms timer waited more than half a second. In a server, every other client would wait too. The async version runs the hashing on the libuv thread pool and the event loop stays free:
import { pbkdf2 } from 'node:crypto';
import { promisify } from 'node:util';
const pbkdf2Async = promisify(pbkdf2);
const start = performance.now();
setTimeout(() => {
console.log(`timer fired after ${Math.round(performance.now() - start)} ms (wanted 10)`);
}, 10);
await pbkdf2Async('password', 'salt', 1_000_000, 64, 'sha512');
console.log(`async work took ${Math.round(performance.now() - start)} ms`);
timer fired after 19 ms (wanted 10)
async work took 597 ms
Common sources of blocking:
*Syncfunctions (readFileSync,execSync,pbkdf2Sync,scryptSync) in request handlers. They are fine at startup and in CLI scripts.JSON.parse/JSON.stringifyof multi-megabyte payloads- regular expressions with catastrophic backtracking on user input (ReDoS)
- long loops over big arrays, sorting huge lists, image processing in pure JavaScript
Move heavy pure-JavaScript work to a worker_threads worker (see Multithreading) and read more about the loop in Event Loop.
Losing this when passing a method
Passing obj.method as a callback passes the function alone. It's called later without obj, so this is undefined:
class Counter {
count = 0;
increment() {
this.count++;
console.log('count is', this.count);
}
}
const c = new Counter();
setTimeout(c.increment, 10); // `this` is not c
count is NaN
With setTimeout, Node.js calls the callback with this set to the Timeout object, so this.count++ silently turns into NaN. In other places (e.g. arr.map(c.increment)) you get TypeError: Cannot read properties of undefined.
Wrap the call in an arrow function or use bind:
const c = new Counter();
setTimeout(() => c.increment(), 10);
setTimeout(c.increment.bind(c), 20);
count is 1
count is 2
'error' events without a listener
EventEmitter treats the 'error' event specially. If you emit 'error' and no listener is registered, the error is thrown:
import { EventEmitter } from 'node:events';
const job = new EventEmitter();
job.on('done', () => console.log('done'));
job.emit('error', new Error('disk full')); // no 'error' listener
console.log('not reached');
file:///app/p09.mjs:6
job.emit('error', new Error('disk full')); // no 'error' listener
^
Error: disk full
at file:///app/p09.mjs:6:19
Emitted 'error' event at:
at file:///app/p09.mjs:6:5
Node.js v24.20.0
Streams, sockets, HTTP requests and child processes are all event emitters. A network error on a socket without an 'error' listener takes down the whole server. Always attach one:
import { EventEmitter } from 'node:events';
const job = new EventEmitter();
job.on('error', (err) => console.log('job failed:', err.message));
job.emit('error', new Error('disk full'));
console.log('still running');
job failed: disk full
still running
Listener leaks
The other common emitter bug is adding listeners in a function that runs many times, for example per request, and never removing them:
import { EventEmitter } from 'node:events';
const bus = new EventEmitter();
function handleRequest() {
// adds a new listener on every request and never removes it
bus.on('config-changed', () => {});
}
for (let i = 0; i < 11; i++) handleRequest();
(node:30400) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 config-changed listeners added to [EventEmitter]. MaxListeners is 10. Use emitter.setMaxListeners() to increase limit
(Use `node --trace-warnings ...` to show where the warning was created)
Every listener keeps its closure alive, so memory grows forever. Don't silence the warning with setMaxListeners(0). Use once(), remove the listener with off() when done, or register it once at startup. More in Event Emitters.
Ignoring stream errors with .pipe()
.pipe() does not forward errors. An error in any stream is an unhandled 'error' event, and the other streams are not closed:
import { createReadStream, createWriteStream } from 'node:fs';
import { createGzip } from 'node:zlib';
createReadStream('does-not-exist.log')
.pipe(createGzip())
.pipe(createWriteStream('out.log.gz'));
node:events:505
throw er; // Unhandled 'error' event
^
Error: ENOENT: no such file or directory, open '/app/does-not-exist.log'
Emitted 'error' event on ReadStream instance at:
at emitErrorNT (node:internal/streams/destroy:170:8)
at emitErrorCloseNT (node:internal/streams/destroy:129:3)
at process.processTicksAndRejections (node:internal/process/task_queues:90:21) {
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: '/app/does-not-exist.log'
}
Use pipeline from node:stream/promises. It forwards errors from any stage, destroys all streams on failure and returns a promise you can await:
import { createReadStream, createWriteStream } from 'node:fs';
import { pipeline } from 'node:stream/promises';
import { createGzip } from 'node:zlib';
try {
await pipeline(
createReadStream('does-not-exist.log'),
createGzip(),
createWriteStream('out.log.gz'),
);
} catch (err) {
console.log('pipeline failed:', err.code);
}
pipeline failed: ENOENT
Corrupting multi-byte characters in chunks
Streams deliver data as Buffer chunks, and chunk boundaries don't respect UTF-8 characters. Converting each chunk to a string on its own (which text += chunk does) breaks characters that are split across two chunks:
import { Readable } from 'node:stream';
// 'é' is 2 bytes in UTF-8: 0xC3 0xA9. Split it across two chunks.
const bytes = Buffer.from('café', 'utf8');
const stream = Readable.from([bytes.subarray(0, 4), bytes.subarray(4)]);
let text = '';
stream.on('data', (chunk) => {
text += chunk; // Buffer -> string conversion of each chunk separately
});
stream.on('end', () => console.log(text));
caf��
This bug passes every test with ASCII data and only appears in production with real user text and large inputs. Either let the stream decode the text with setEncoding('utf8'), which handles split characters, or collect Buffers and decode once:
import { Readable } from 'node:stream';
const bytes = Buffer.from('café', 'utf8');
const mk = () => Readable.from([bytes.subarray(0, 4), bytes.subarray(4)]);
// Option 1: let the stream decode UTF-8 for you
const s1 = mk();
s1.setEncoding('utf8');
let text = '';
for await (const chunk of s1) text += chunk;
console.log(text);
// Option 2: collect Buffers, decode once at the end
const chunks = [];
for await (const chunk of mk()) chunks.push(chunk);
console.log(Buffer.concat(chunks).toString('utf8'));
café
café
The same applies to HTTP request bodies, child process output and sockets.
Relative paths are relative to the working directory
fs functions resolve relative paths against process.cwd(), the directory where node was started, not against the directory of the script. The program works when started from one directory and fails from another:
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
console.log('cwd: ', process.cwd());
console.log('dirname:', import.meta.dirname);
// relative to the current working directory, not to this file
try {
readFileSync('./data.txt', 'utf8');
} catch (err) {
console.log('relative path:', err.code);
}
// relative to this file
const text = readFileSync(join(import.meta.dirname, 'data.txt'), 'utf8');
console.log('import.meta.dirname:', text.trim());
Running node sub/app.mjs from the project root, with data.txt next to app.mjs:
cwd: /app
dirname: /app/sub
relative path: ENOENT
import.meta.dirname: hello
For files that ship with your code, build the path from import.meta.dirname (ES modules) or __dirname (CommonJS). Note that import and require() paths are already relative to the current file. Only fs and similar APIs use the working directory.
__dirname and require in ES modules
ES modules don't have the CommonJS variables __dirname, __filename, require, module and exports:
console.log(typeof __dirname, typeof require);
console.log(__dirname);
undefined undefined
file:///app/p12.mjs:2
console.log(__dirname);
^
ReferenceError: __dirname is not defined in ES module scope
Use import.meta.dirname and import.meta.filename (Node.js 20.11+). If you really need require, for example to load a JSON file synchronously, create one with createRequire:
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
const pkg = require('./package.json');
console.log(pkg.name);
console.log(import.meta.filename.endsWith('p12b.mjs'));
pitfalls-demo
true
Whether a .js file is an ES module or CommonJS depends on the "type" field in the nearest package.json. See Require and How modules are loaded.
Calling process.exit() too early
process.exit() stops the process immediately. Pending timers, unfinished file writes, open database transactions and buffered log output (when stdout is a pipe) are all dropped:
setTimeout(() => console.log('flushing logs...'), 50);
console.log('work finished');
process.exit(0); // the timer never runs
work finished
To report a failure, set process.exitCode and let Node.js exit on its own once the event loop is empty:
setTimeout(() => console.log('flushing logs...'), 50);
console.log('work finished');
process.exitCode = 1; // exit with code 1 once the event loop is empty
work finished
flushing logs...
The exit code is still 1. If the process doesn't exit by itself, something is still open (a server, a database pool, an interval). Close it explicitly. See Graceful Shutdown.
Quick checklist
awaitevery promise, or handle it with.catch().- No
asynccallbacks inforEach. Usefor...oforPromise.all. - Start independent operations together with
Promise.all. Limit concurrency for large lists. - Use
Promise.allSettledwhen partial results are fine. - Put
try/catchinside callbacks, or switch to promise APIs. return callback(err)in callback-style code.- No
*Synccalls or heavy CPU work in request handlers. - Bind methods passed as callbacks.
- Attach an
'error'listener to every emitter, stream and socket. - Use
pipeline()instead of.pipe(). - Decode text with
setEncoding()orBuffer.concat(), never chunk by chunk. - Build file paths from
import.meta.dirname. - Prefer
process.exitCodeoverprocess.exit().