Get all files in directory
This code snippet recursively examines a directory, and all it’s subdirectories, to identify files. It returns an array of objects with the fullpath, and the filename as strings.
import FS from 'fs';
import Path from 'path';
/**
* Recursively retrieve a list of files from the specified directory.
* @param {String} directory
* @returns An array of {fullpath, name} obects.
*/
function getFiles(directory = "."){
const dirEntries = FS.readdirSync(directory, { withFileTypes: true });
const files = dirEntries.map((dirEntry) => {
return dirEntry.isDirectory() ? getFiles(resolved) : {fullpath : resolved, name : dirEntry.name};
});
return files.flat();
}
export default getFiles;
The filesystem library for JS provides the synchronous read directory function (line 10). Setting withFileTypes to true in the options, directs readdirSync to return directory entry objects.
The array’s map method passes in each directory entry object into a provided callback function (lines 12-15). The return value of this function is inserted into a new array.
The ternary operator on line 12 is the callback, and works as follows:
If the dirEntry object is not a function then add the fullpath and name to the array. If it is, then recursively call the getFiles function and and add the result to the array. Because the recursive call nests arrays into arrays, we call the array’s flat method which creates a new single 1-dimensional array.