How to use the Node.js fs module with async/await

By

Learn how to use the Node.js fs module with async/await through the promise-based node:fs/promises API, so you can await calls like fs.readdir() directly.

~~~

Node.js built-in modules famously started out callback-based, not promise-based.

This is for historical reasons, as those modules were created before promises were a thing.

We’ve had promisify for quite some time, but when I wrote this post I had just found out Node.js also provides a promise-based fs API.

I thought it was new but it’s been introduced in Node.js 10 (2018, it’s been a while!).

Here’s how to use it, on any current Node.js (26, or the 24 LTS line):

import * as fs from 'node:fs/promises';

| Note the node:fs convention which identifies native modules

Now you can use any of the fs methods with promises or await:

const posts = await fs.readdir('content')

Back then I wasn’t sure this would be ported to other native modules. It was. Node now ships a /promises export for several built-ins, including node:dns/promises, node:timers/promises, node:stream/promises and node:readline/promises, so check the Node docs for one before you fall back to util.promisify().

Tagged: Node.js · All topics

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about node: