Get All Files In Directory Using Nodejs With Recursive Function
By onjsdev
Jan 1st, 2024
The fs module in nodejs is a built-in package that has very useful methods to handle filesystem-related tasks. In this article, we will show you how to get all files in a directory and in its subdirectories using nodejs with the fs module.
With the readdir method, we can get the files under a directory. However, in case the Directory has subdirectories we may need to use a recursive method.
Input / Output For Files
Before we begin, let's take a look at what the output will be for a given input after running the function. As shown below we will get an array containing all the files in a directory for a given path.
--Input --Output
icons ['home.svg','logo.svg',
|-home.svg 'instagram-dark.svg',
|-logo.svg 'twitter.svg']
|social
|dark
|-instagram-dark.svg
|-twitter.svg
How to Get All Files Recursively In Directory With Nodejs
As we've mentioned above, we will use the readdir method from the fs module. To use async functions instead of callback, firstly, we will promisfy it and then create our function. We have commented each line on code snippet to make it clear. Let's see our recursive approach.
const fs = require('fs');
/* we want to use async functions not callback, so
promisfy the methods */
const { promisify } = require('util');
const readdir = promisify(fs.readdir);
async function listFiles(folderPath) {
let files = [];
// Read files and subdirectories
const dirs = await readdir(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 (fs.lstatSync(fullPath).isDirectory()) {
/* run the function again and save files in subdirectories
by merging old array and new files */
// [1,2] -> concat [3,4] -> [1,2,3,4]
files = files.concat(await listFiles(fullPath));
} else {
// Add to files to the array
files.push(dirs[i]);
}
}
return files;
}
Test Recursive Function To List Files
The function we have created is an async function which means return a promise so, get the output with then method for a given directory path.
listFiles(__dirname + '/icons').then((files) => console.log(files));
/* ['home.svg','logo.svg','instagram-dark.svg','twitter.svg'] */
Conclusion
That's all. In this article, we have shown you how to get all files recursively in a directory and in its subdirectories using the nodejs fs module.
Thank you for reading.