CodePark/ questions / Errors, process & signals
START PRACTICINGPRACTICE
Backend question · Node.js › Errors, process & signals

What is the error-first callback convention in Node.js?

fs.readFile("data.json", "utf8", (err, text) => {
  if (err) return handle(err);
  use(JSON.parse(text));
});

The callback is the last argument, and Node calls it with the error first and the results after it: callback(err, data). If the operation succeeds, err is null or undefined.

This is how Node's classic async APIs work.

The rules for the caller and the API:

  • The caller must check err first and return early if it is set. A try/catch around the original call cannot catch an error thrown later inside the async operation.
  • The API must call the callback exactly once.
  • The API should call the callback asynchronously, even when it knows the result at once. This way callers always see the same behavior.

Today most core APIs also have promise versions, such as fs/promises. util.promisify turns any error-first callback function into a function that returns a promise.

  • The signature is callback(err, result), and the callback is the last argument.
  • err is null on success, so check it first and return early.
  • A try/catch around the call cannot catch async errors.
  • Call the callback exactly once, and always asynchronously.
  • util.promisify turns callback functions into promise functions.