Listing All Files Recursively in a Directory In NodeJs
Jan 07 2024
The fs module is a built-in module in Node.js that provides filesystem-related functions for reading and writing to files, and interacting with the file system.
Here is an example of how you can use the fs module to list all the files in a directory and its subdirectories in Node.js
Before we start let's explain the methods we will use to create code snippet
readdirSync()
is for getting files and folders in a directorystatSync().isDirectory()
is for checking if a path given is a directory or fileconcat()
is for combining different arrays into an array
So here is our solution to get all files and folders in a directory.
const { readdirSync, lstatSync } = require("fs");
function listFiles(folderPath) {
let files = [];
// Read files and subdirectories
const dirs = readdirSync(folderPath);
for (let i = 0; i < dirs.length; i++) {
// Get full path of files and subdirectories
const fullPath = folderPath + `/${dirs[i]}`;
// If the directory has subdirectory
if (lstatSync(fullPath).isDirectory())
files = files.concat(listFiles(fullPath));
else files.push(dirs[i]);
}
return files;
}
// Run the function
console.log(listFiles("/path/to/folder"));
As you realize the function above is recursive which means, if current content in a directory is a subdirectory then it runs again and save the files if not , only save the files.
After the function execution is finished, it returns the merged array containing all files and folders in a directory.
Conclusion
In conclusion, the fs module can be used to list all the files in a directory and its subdirectories in Nodejs by creating recursive method, as demonstrated in the example provided.
If you want to learn more about nodejs, then you can see the following articles:
Thank you for reading.