Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get a list of the names of all files present in a directory in Node.js?

I'm trying to get a list of the names of all the files present in a directory using Node.js. I want output that is an array of filenames. How can I do this?

like image 469
resopollution Avatar asked Apr 28 '10 06:04

resopollution


People also ask

How do you get a list of the names of all files present in a directory in JavaScript?

To get a list of the names of all files present in a directory in Node. js, we can call the readdir method. const testFolder = './folder/path'; const fs = require('fs'); fs. readdir(testFolder, (err, files) => { files.

How do I read a directory in node JS?

The fs. readdir() method is used to asynchronously read the contents of a given directory. The callback of this method returns an array of all the file names in the directory. The options argument can be used to change the format in which the files are returned from the method.


2 Answers

You can use the fs.readdir or fs.readdirSync methods. fs is included in Node.js core, so there's no need to install anything.

fs.readdir

const testFolder = './tests/'; const fs = require('fs');  fs.readdir(testFolder, (err, files) => {   files.forEach(file => {     console.log(file);   }); }); 

fs.readdirSync

const testFolder = './tests/'; const fs = require('fs');  fs.readdirSync(testFolder).forEach(file => {   console.log(file); }); 

The difference between the two methods, is that the first one is asynchronous, so you have to provide a callback function that will be executed when the read process ends.

The second is synchronous, it will return the file name array, but it will stop any further execution of your code until the read process ends.

like image 92
Christian C. Salvadó Avatar answered Oct 06 '22 10:10

Christian C. Salvadó


IMO the most convenient way to do such tasks is to use a glob tool. Here's a glob package for node.js. Install with

npm install glob 

Then use wild card to match filenames (example taken from package's website)

var glob = require("glob")  // options is optional glob("**/*.js", options, function (er, files) {   // files is an array of filenames.   // If the `nonull` option is set, and nothing   // was found, then files is ["**/*.js"]   // er is an error object or null. }) 

If you are planning on using globby here is an example to look for any xml files that are under current folder

var globby = require('globby');  const paths = await globby("**/*.xml");   
like image 36
KFL Avatar answered Oct 06 '22 09:10

KFL