Skip to content
jshacks.dev
Async

Error-First Callbacks in Node.js

Learn the Node.js error-first callback convention, how to write and consume it correctly, and how util.promisify turns one into a promise.

7 min read
Summarize in AI
Flat illustration of a log with a failing line and a wrench, with the Node.js, JavaScript, TypeScript and npm logos.

Almost every older Node.js API ends with a function whose first parameter is an error, and almost every bug involving one comes from forgetting that. The convention is simple: the callback receives (error, result), where error is null on success and an Error object on failure. This post explains the contract as it applies to Node.js 24, how to write a function that follows it, the checks you must make when consuming one, the three ways people break it and how util.promisify converts one into a promise. If you only call modern node:fs/promises functions you may never write one, but you will read them for years, since the convention is baked into streams, child_process, crypto and thousands of packages.

The contract

An error-first callback has three rules.

  1. The callback is the last argument of the function that takes it.

  2. The first argument of the callback is the error, null or undefined when there is none.

  3. The callback is called exactly once, either with an error or with results.

JavaScript
import { readFile } from "node:fs";

readFile("/does/not/exist.txt", "utf8", (error, text) => {
  if (error) {
    console.log("code:", error.code);
    console.log("message:", error.message);
    console.log("text is:", text);
    return;
  }

  console.log("never printed");
});
Text
code: ENOENT
message: ENOENT: no such file or directory, open '/does/not/exist.txt'
text is: undefined

On failure the result argument is undefined, so code that uses it without checking error first fails on the wrong line. The error.code is the stable value to branch on, since messages can change between versions.

Why the error comes first

The error sits in the first position so it cannot be skipped by accident. A callback written as (data) => ... would be missing the slot and would treat the error as data. Putting the error first means every handler starts with the same line, if (error), and a reader can scan for it. The design also keeps the position stable when a function returns several values: the error is always argument one, and results follow as arguments two, three and so on.

JavaScript
import { exec } from "node:child_process";

exec("node --version", (error, stdout, stderr) => {
  if (error) {
    console.log("failed with code", error.code);
    return;
  }

  console.log("stdout:", stdout.trim());
  console.log("stderr empty:", stderr === "");
});
Text
stdout: v24.0.0
stderr empty: true

The version printed depends on the Node.js you run; the shape is what matters. exec passes two results after the error.

Writing a function that follows the contract

When you write one, follow three habits. Accept the callback last, call it once, and never throw for an operational failure. Pass the failure to the callback instead.

JavaScript
function parseJsonAsync(text, callback) {
  setTimeout(() => {
    let value;

    try {
      value = JSON.parse(text);
    } catch (error) {
      callback(error);
      return;
    }

    callback(null, value);
  }, 0);
}

parseJsonAsync('{"ok": true}', (error, value) => {
  console.log(error, value);
});

parseJsonAsync("{bad json", (error, value) => {
  console.log(error.name, value);
});
Text
null { ok: true }
SyntaxError undefined

The try/catch is inside the timer callback, because the caller's try/catch could never catch an error thrown later. The function parses inside the asynchronous task and routes the failure to the callback. Note the return after the error call: without it, callback(null, value) would run as well with value undefined, and the callback would be invoked twice.

Calling the callback consistently

A function must not call its callback synchronously in one branch and asynchronously in another. If it does, the code after the call runs in a different order depending on a condition the caller cannot see.

JavaScript
const cache = new Map([["a", 1]]);

function lookupBad(key, callback) {
  if (cache.has(key)) {
    callback(null, cache.get(key)); // synchronous
    return;
  }
  setTimeout(() => callback(null, "loaded"), 0); // asynchronous
}

lookupBad("a", () => console.log("callback ran"));
console.log("after call");
Text
callback ran
after call

Here the callback ran before the line that follows. With a cache miss, the order flips. The fix is to defer the synchronous branch.

JavaScript
function lookup(key, callback) {
  if (cache.has(key)) {
    queueMicrotask(() => callback(null, cache.get(key)));
    return;
  }
  setTimeout(() => callback(null, "loaded"), 0);
}

lookup("a", () => console.log("callback ran"));
console.log("after call");
Text
after call
callback ran

Now it is always asynchronous, and the caller can rely on the order. Node.js uses process.nextTick for this in its own core, and queueMicrotask is the standard equivalent.

Consuming one correctly

A handler should do four things in order: check the error, stop on it, use the results and avoid throwing from inside the callback.

JavaScript
import { readFile } from "node:fs";

function loadSettings(path, done) {
  readFile(path, "utf8", (error, text) => {
    if (error) {
      done(error);
      return;
    }

    let settings;

    try {
      settings = JSON.parse(text);
    } catch (parseError) {
      done(parseError);
      return;
    }

    done(null, settings);
  });
}

loadSettings("/missing.json", (error, settings) => {
  console.log(error ? error.code : "ok", settings);
});
Text
ENOENT undefined

loadSettings is itself error-first, so it composes: its callers use the same pattern. Forwarding the error with done(error) and returning is the idiom for passing a failure up the chain.

Three ways people break it

Checking truthiness of the result instead of the error. Writing if (!data) treats an empty file or a result of 0 as a failure. Always test error.

Throwing from inside the callback. A throw inside an asynchronous callback is an uncaught exception, and the process exits unless a handler exists for uncaughtException. Pass the error forward instead.

Calling twice. Missing return after the error branch runs both paths, as above. A defensive wrapper can guard against it.

JavaScript
function once(fn) {
  let called = false;
  return (...args) => {
    if (called) return;
    called = true;
    fn(...args);
  };
}

const done = once((error, value) => console.log(error ? error.message : "ok", value));

done(new Error("first"));
done(null, "second");
Text
first undefined

Only the first call went through, and the second was ignored.

Converting to promises

util.promisify turns an error-first function into one that returns a promise. The error becomes a rejection and the first result becomes the fulfillment value.

JavaScript
import { promisify } from "node:util";
import { readFile } from "node:fs";

const readFileAsync = promisify(readFile);

try {
  await readFileAsync("/missing.txt", "utf8");
} catch (error) {
  console.log("caught", error.code);
}
Text
caught ENOENT

It works for any function that follows the contract exactly: callback last, error first. A function that breaks the contract, such as one that passes a result first, will not convert correctly. For exec, which passes two results, the fulfillment value is an object with stdout and stderr, because that function carries a custom promisified version.

For a function of your own that does not use util.promisify, wrap it manually.

JavaScript
function parseJsonPromise(text) {
  return new Promise((resolve, reject) => {
    parseJsonAsync(text, (error, value) => {
      if (error) reject(error);
      else resolve(value);
    });
  });
}

console.log(await parseJsonPromise('{"n": 5}'));
Text
{ n: 5 }

When to prefer something else

For new code, use the promise versions in node:fs/promises, node:timers/promises and node:dns/promises. They throw rejections that try/catch handles, and they cannot be called twice. The error-first form remains the right shape for APIs that report many results over time, such as streams, where pipeline accepts a final error-first callback, or for libraries that must support old Node.js versions.

Where you will still meet this style

Error-first callbacks are not going away soon. Streams report completion through them, and stream.pipeline accepts a final error-first callback, though a promise version exists in node:stream/promises. Older database drivers, logging transports and build tools keep the shape because they must support old Node.js versions, and a convention that thousands of packages share is hard to retire.

When you work with one, read the documentation for two details that the convention does not settle: whether the callback can be called more than once, and what the result arguments are. Streams and event-like APIs may call a callback repeatedly, while one-shot functions call it once. The convention also leaves open whether an error means nothing was done or that something was partly done, which matters for file writes and network calls. Treat the error as a signal to stop and report, and do not assume the state of the world is clean afterwards.

Testing a callback-style function

A function that takes an error-first callback is tested by wrapping the call in a promise, so the test can await the result. Pass a callback that resolves with an object holding both arguments, and assert on the pair. Write one test for the success path, where the error is null, and one for each failure you document, checking the error's code and not its message. Add a test that the callback runs exactly once, by counting calls and waiting a few milliseconds before asserting, since a double call is the most common defect and shows up only after the first one has passed. And test that the callback is always asynchronous, by recording whether it ran before the line that follows the call. A function that sometimes calls back synchronously will pass the other tests and still break its callers, and that test is the only one that catches it.

Also inNode.js
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.