Hemanth's Scribes

node

Promisified Node Builtins

Author Photo

Hemanth HM

Thumbnail

At any point in time if you were to promisify a function you can use util.promisify, for example:

import util from "util";
import fs from "fs";

const readFile = util.promisify(fs.readFile);
readFile("/tmp/foo.txt", "utf-8")
  .then((buffer) => {
    // we have the content
  })
  .catch((error) => {
    // Handle the error
  });
// Maybe
(async () => {
  const content = await readFile("/tmp/foo.txt", "utf-8").catch((err) => {});
})();

But interestingly there are few builtins that are already promisified for us:

require("module")
  .builtinModules
  .filter((module) => /promises/.test(module));
// -> [ 'dns/promises', 'fs/promises', 'stream/promises', 'timers/promises' ]

Built-in Promisified Modules (Node v16+)

Sample Usage

timers/promises

import { setTimeout, setImmediate, setInterval } from "timers/promises";

const res = await setTimeout(100, "42");

### dns/promises
javascript
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 }

### stream/promises
javascript
const { pipeline } = require("stream/promises");
const fs = require("fs");

async function convert() {
  await pipeline(
    fs.createReadStream("english.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 ✅.");
}

convert().catch(console.error);

### fs/promises
javascript
const readFile = require("fs/promises").readFile;

(async () => {
  const content = await readFile("/tmp/foo.txt", "utf-8").catch((err) => {});
})();
#node#javascript#promises
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.