How to use Node.js filesystem with async / await?

Sometimes, we want to use Node.js filesystem with async / await.

In this article, we’ll look at how to use Node.js filesystem with async / await.

How to use Node.js filesystem with async / await?

To use Node.js filesystem with async / await, we can use the fs.promises module.

For instance, we write

import fs from 'fs';
const fsPromises = fs.promises;

const listDir = async () => {
  try {
    return fsPromises.readdir('path/to/dir');
  } catch (err) {
    console.error('Error occured while reading directory!', err);
  }
}

listDir();

to define the listDir function that calls fsPromises.readdir with the path we want to list.

We use await to get the result resolved by the promise returned.

And we use try and catch to catch any errors if the promise is rejected.

Conclusion

To use Node.js filesystem with async / await, we can use the fs.promises module.