At any point in time if you were to promisify a function you can use util.promisify
, for example:
1
2
3
4
| import util from "util";
import fs from "fs";
const readFile = util.promisify(fs.readFile);
|
1
2
3
4
5
6
7
| readFile("/tmp/foo.txt", "utf-8")
.then((buffer) => {
// we have the content
})
.catch((error) => {
// Handle the error
});
|
1
2
3
4
| // Maybe
(async () => {
const content = await readFile("/tmp/foo.txt", "utf-8").catch((err) => {});
})();
|
But interesting there are few builtins that are already promisifed for us:
1
2
3
4
| require("module")
.builtinModules
.filter((module) => /promises/.test(module));
// -> [ 'dns/promises', 'fs/promises', 'stream/promises', 'timers/promises' ]
|
In the latest version of node v16
we have the below:
Sample usage:
1
2
3
4
| // mjs
import { setTimeout, setImmediate, setInterval } from "timers/promises";
const res = await setTimeout(100, "42");
|
1
2
3
4
| const dnsPromises = require("dns/promises"); // require('dns').promises
const lookup = dnsPromises.lookup;
const lookupResp = await lookup("127.0.1.1");
// lookupResp -> { address: '127.0.1.1', family: 4 }
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| const { pipeline } = require("stream/promises");
const fs = require("fs");
async function convert() {
await pipeline(
fs.createReadStream("enlgish.txt"),
async function* (source) {
source.setEncoding("utf8");
for await (const chunk of source) {
yield translate(chunk, "EN2FR"); // imaginary translate method
}
},
fs.createWriteStream("french.txt")
);
console.log("Pipeline ✅.");
}
run().catch(console.error);
|
1
2
3
4
| const readFile = require("fs/promises").readFile;
(async () => {
const content = await readFile("/tmp/foo.txt", "utf-8").catch((err) => {});
})();
|
Hope to see more such built-in promise APIs!