Do you need to get all files present in the directory or you want to scan a directory for files using node.js, then you’re on the correct web page because in this Nodejs How to Tutorial, we will learning How to get the list of all files in a directory in Node.js.
We will be using Node.js fs core module to get all files in the directory, we can use following fs methods.
- fs.readdir(path, callbackFunction) – This method will read all files in the directory.You need to pass directory path as the first argument and in the second argument, you can any callback function.
- path.join([…paths]) – This method of node.js path module, we will be using to get the path of the directory and This will join all given path segments together.
Steps to get list of all the files in a directory in Node.js
- Load all the required Nodejs Packages using “require”.
- Get the path of the directory using path.join() method.
- Pass the directory path and callback function in fs.readdir(path, callbackFunction) Method.
- The callback function should have error handling and result handling logic.
- inside callback function handle the error and run forEach on the array of files list from the directory.
- Apply your logic for each file or all the files inside the forEach function.
Full code:
//requiring path and fs modules var path = require('path'); var fs = require('fs'); //joining path of directory var directoryPath = path.join(__dirname, 'Documents'); //passsing directoryPath and callback function fs.readdir(directoryPath, function (err, files) { //handling error if (err) { return console.log('Unable to scan directory: ' + err); } //listing all files using forEach files.forEach(function (file) { // Do whatever you want to do with the file console.log(file); }); });
for example, we will scan the directory containing following files:
we will run our nodejs code using node file.js and For results see below:
If you have any queries, please comment below and thanks for reading this tutorial.
hi,how to read only methods /functions from a js file