Node.js: promisify API

July 18, 2021

Version after version the Node.js API is migrating to promises replacing the common and old error-first callback style. But even the modules that are still not migrated can be converted to promises using the function promisify provided by the util module. For example, we can promisify the function to read a file.

"use strict"; const fs = require("fs"); const util = require("util"); const readFile = (path) => { return util.promisify(fs.readFile)(path, "utf-8"); };

And use it

readFile("/path/to/file") .then((content) => { // do something with content }) .catch((error) => { // handle the error });

Did you find this post useful? What about Buy Me A Coffee

A photo of Elia Contini
Written by
Elia Contini
Sardinian UX engineer and a Front-end web architect based in Switzerland. Marathoner, traveller, wannabe nature photographer.