As of now, most Node callback-based APIs should be manually promisified in order to make use of promises.
util.promisify
is available since Node 8 (also polyfillable) and allows to promisify any APIs that use error-first callbacks, including built-in fs
:
const { promisify } = require('util');
const fs = require('fs');
const readFile = promisify(fs.readFile);
readFile(file).then(console.log);
Some APIs that use non-error-first callbacks support it too via util.promisify.custom
symbol, e.g. setTimeout
:
promisify(setTimeout)(100).then(...);
fs.promises experimental API is available since Node 10 (polyfillable in Node 8 and higher) and contains promisified fs
module, as already mentioned in another question:
const fsp = require('fs').promises;
fsp.readFile(file).then(console.log);
For batch promisification third-party tools like pify can be used.
Third-party promisification packages are available for most built-in and popular third-party callback-based packages that can be converted to promises, e.g. fs-extra, which is a preferable drop-in replacement for fs
that includes essential graceful-fs
package.