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
errfirst and return early if it is set. Atry/catcharound 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. erris null on success, so check it first and return early.- A
try/catcharound the call cannot catch async errors. - Call the callback exactly once, and always asynchronously.
util.promisifyturns callback functions into promise functions.
Read more