Categories
JavaScript Answers

How to use filesystem in Node.js with async and await?

Spread the love

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

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

How to use filesystem in Node.js with async and await?

To use filesystem in Node.js with async and 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", err);
  }
};

listDir();

to create the listDir function that calls fsPromises.readdir to get the contents listing of the directory.

We return the promise returned by readdir to return the results in the promise.

Conclusion

To use filesystem in Node.js with async and await. we can use the fs.promises module.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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