The File System Promises API
In the following code snippets, I'll be using the fs Promises API.
It's available to you if you're rocking at least Node.js v10.
const { promises: fs } = require("fs");
Separating the directory entries
To be able to separate the entries, we have to explicitly ask for all information about the file type.
const entries = await fs.readdir(path, { withFileTypes: true });
If we now want to separate the entries, we can just do this by calling the isDirectory
method.
const folders = entries.filter(entry => entry.isDirectory());
const files = entries.filter(entry => !entry.isDirectory());
Getting the files recursive
If we now combine the previously mentioned ways to separate the files, put everything in a function and call this function recursively for every subdirectory, we are able to get all files within the current directory and all subdirectories.
async function getFiles(path = "./") {
const entries = await fs.readdir(path, { withFileTypes: true });
// Get files within the current directory and add a path key to the file objects
const files = entries
.filter(entry => !entry.isDirectory())
.map(file => ({ ...file, path: path + file.name }));
// Get folders within the current directory
const folders = entries.filter(entry => entry.isDirectory());
for (const folder of folders)
/*
Add the found files within the subdirectory to the files array by calling the
current function itself
*/
files.push(...await getFiles(`${path}${folder.name}/`));
return files;
}
Top comments (2)
Change first 3 lines with -
const { readdir } = require('fs/promises');
async function getFiles(path = "./") {
const entries = await readdir(path, { withFileTypes: true });
There is error in following line -
const entries = await fs.readdir(path, { withFileTypes: true });
It needs callback