Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท Concepts and Pitfalls

Error-first callbacks in Node.js

The Node.js error-first callback convention explained: argument order, calling the callback once, sync versus async consistency, and converting with util.promisify.

Before promises, Node's asynchronous APIs shared one convention: the error-first callback. The callback is the last argument of the function, and its first parameter is reserved for an error. If the operation failed, that parameter holds an Error object; if it succeeded, it is null (or undefined), and the results follow from the second parameter on.

NODE
fs.readFile(path, (err, data) => {
  if (err) return handle(err);
  use(data);
});

The convention is still everywhere: older libraries, event-style APIs and many core functions (fs.readFile, crypto.pbkdf2, dns.lookup) keep the callback form next to a promise form. Because every function behaves the same way, helpers like util.promisify() can convert them automatically.

Try it

Node.js Writing and calling an error-first function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js Zalgo and promisify

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The rules

  • Callback last, error first. fn(arg1, arg2, (err, result) => {}). Always check err before using the result.
  • Call the callback exactly once. Calling it twice runs the continuation twice; never calling it leaves the caller hanging. After calling it for an error, return so the success path does not also run.
  • Be consistently asynchronous. A function must never call its callback synchronously in some cases and asynchronously in others (nicknamed "releasing Zalgo"). Callers cannot reason about ordering when that happens. Use process.nextTick() or setImmediate() to defer cache hits and validation errors.
  • Report operational errors through the callback, not by throwing. A try/catch around the call cannot catch an error raised after the function has returned. Programming errors (wrong argument type) may still throw synchronously; that is how core APIs behave.
  • Pass null for no error, and results as separate arguments after it. Multiple results are fine ((err, bytesRead, buffer)), but a single result object is easier to convert.
  • Errors are Error objects, ideally with a code property that callers can test, such as ENOENT or ERR_INVALID_ARG_TYPE.

Syntax

NODE
// callback signature
type Callback<T> = (err: Error | null, result?: T) => void;

util.promisify(original: (...args, cb: Callback) => void): (...args) => Promise<T>
util.callbackify(original: (...args) => Promise<T>): (...args, cb: Callback) => void

promisify resolves with the second argument, or rejects with the error. Functions with several results can define util.promisify.custom (as fs.exists and child_process.exec do) to resolve with an object. callbackify calls the callback with the rejection reason as err; a falsy rejection reason is wrapped in an Error with the code ERR_FALSY_VALUE_REJECTION.

Usage notes

  • Callback hell comes from nesting; fix it with named functions, early returns, or promises and async/await.
  • Throwing inside a callback that runs from the event loop is an uncaught exception and ends the process unless a handler exists; always handle err and guard your own code.
  • Event-style errors use a different channel: emitters emit 'error' events instead of passing callbacks. See The error event.
  • Prefer the promise form in new code (see Callback, promise and sync APIs), and keep callbacks for event handlers and interop.
  • Test with a real error path. Callbacks that look right often forget return after the error branch.