/

How to Use the Node.js fs Module with async/await

How to Use the Node.js fs Module with async/await

Node.js built-in modules are well-known for not being promise-based. This was because these modules were created before promises became popular. Although the promisify function has been available for some time, Node.js introduced a new promise-based API starting from version 10.

Currently, this new API is only available for the fs built-in module, and it remains uncertain whether it will be implemented for other native modules in the future.

To utilize this new API, follow these steps:

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

Take note of the node:fs convention, which is now used to identify native modules.

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

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

With these new capabilities, you can leverage the power of async/await and simplify your asynchronous code with the fs module.

tags: [“Node.js”, “fs module”, “async/await”, “promises”]