Categories
Node.js Quick Tips Quick Tips

Take advantage of promise-based APIs in Node.js

2 min read

This blog post is part of the series What’s new in Node.js core?

You can use util.promisify() to wrap callback-based APIs in Node.js core. But did you know that Node.js provides several promise-based APIs too? You can use them with async / await, no wrapping needed!

There are two new promise-based APIs in Node.js core:

There are two other promise-based APIs which you’ll find in Node.js core (they’ve been there since v10.x!):

timers/promises module

/**
 * `timers/promises` module
 *
 * Added: v15.0.0
 * Graduated from experimental: v16.0.0
 * 
 * Can also be loaded with `require()`.
 */

import { setTimeout } from "timers/promises";

const delayedValue = await setTimeout(5000, "some value");

console.log(delayedValue);

Support

Support in Node.js versions:

stream/promises module

/**
 * `stream/promises` module
 *
 * Added: v15.0.0
 *
 * Can also be loaded with `require()`.
 */

import { pipeline } from "stream/promises";

import fs from "fs";
import zlib from "zlib";

try {
	await pipeline(
		fs.createReadStream("archive.tar"),
		zlib.createGzip(),
		fs.createWriteStream("archive.tar.gz")
	);

	console.log("tarred and gzipped file created from tar file");
} catch (error) {
	console.error(error);
}

Support

Support in Node.js versions:

fs/promises module

/**
 * `fs/promises` module
 *
 * Added: v10.0.0 (changed to `fs.promises` in v10.1.0)
 * Exposed as `fs/promises`: v14.0.0
 * 
 * Can also be loaded with `require()`.
 */

import fs from "fs/promises";

const fileContents = await fs.readFile("file.txt", { encoding: "utf-8" });

console.log(fileContents);

Support

Support in Node.js versions:

dns/promises module

/**
 * `dns/promises` module
 *
 * Added: v10.6.0 (as `dns.promises`)
 * Exposed as `dns/promises`: v15.0.0
 * 
 * Can also be loaded with `require()`.
 */

 import dns from "dns/promises";

 const resolver = new dns.Resolver();
 
 const addresses = await resolver.resolve4("nodejs.org");
 
 console.log(addresses);

Support

Support in Node.js versions:

Leave a Reply

Your email address will not be published. Required fields are marked *