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?
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.
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.
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With