How to get folder and file list with Node.js and JavaScript?

Sometimes, we want to get folder and file list with Node.js and JavaScript.

In this article, we’ll look at how to get folder and file list with Node.js and JavaScript.

How to get folder and file list with Node.js and JavaScript?

To get folder and file list with Node.js and JavaScript, we can use the Node.js fs module.

For instance, we write:

const filesystem = require("fs");

const getAllFilesFromFolder = (dir) => {
  let results = [];
  for (const file of filesystem.readdirSync(dir)) {
    const path = `${dir}/${file}`
    const stat = filesystem.statSync(path);
    if (stat && stat.isDirectory()) {
      results = [...results, ...getAllFilesFromFolder(file)]
    } else {
      results.push(file);
    }
  };
  return results;
};

console.log(getAllFilesFromFolder('/bin'))

We loop through the contents of the dir directory with readdirSync.

Then we call statSync with the path to get the stat directory.

And we use its isDirectory method to check if the path is a directory.

If it is, we add it the contents of the child directories to results.

Otherwise, we push the file into results.

Conclusion

To get folder and file list with Node.js and JavaScript, we can use the Node.js fs module.