How to loop through files in a folder Node.js?

Sometimes, we want to loop through files in a folder Node.js.

In this article, we’ll look at how to loop through files in a folder Node.js.

How to loop through files in a folder Node.js?

To loop through files in a folder Node.js, we can use the fs promises module and the for-of loop.

For instance, we write

const loopFiles = async (dir) => {
  try {
    const files = await fs.promises.readdir(dir);

    for (const file of files) {
      const p = path.join(moveFrom, file);
      const stat = await fs.promises.stat(p);

      if (stat.isFile()) {
        console.log("'%s'  file.", fromPath);
      } else if (stat.isDirectory()) {
        console.log("'%s' directory.", fromPath);
      }
    }
  } catch (e) {
    console.error(e);
  }

}

to define the loop function that gets the contents of dir with readdir.

Then we loop through the files array returned from the promise returned by readdir.

Next, we use the for-of loop to loop through files.

We get the full path p with path.join.

And then we call stat with p to get the data about the file or folder.

Then we call isFile to check if the the entity at p is a file.

And we call isDirectory to check if the the entity at p is a folder.

Conclusion

To loop through files in a folder Node.js, we can use the fs promises module and the for-of loop.