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

To loop through files in a folder with Node.js, we use the opendir method.

For instance, we write

const fs = require("fs");

const ls = async (path) => {
  const dir = await fs.promises.opendir(path);
  for await (const dirent of dir) {
    console.log(dirent.name);
  }
};

to call the opendir method with the folder path to return a promise with the items in the folder.

Then we use the for-await-of loop to loop through all the items in the folder.