Categories
JavaScript Answers

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

Spread the love

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.

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 *