DEV Community

Leonard Ginters
Leonard Ginters

Posted on • Updated on

Get files recursive with the Node.js File System (FS)

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");
Enter fullscreen mode Exit fullscreen mode

​ 

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 });
Enter fullscreen mode Exit fullscreen mode

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());
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
vaibhav_arora__ profile image
Vaibhav Arora • Edited

Change first 3 lines with -

const { readdir } = require('fs/promises');
async function getFiles(path = "./") {
const entries = await readdir(path, { withFileTypes: true });

Collapse
 
vaibhav_arora__ profile image
Vaibhav Arora

There is error in following line -
const entries = await fs.readdir(path, { withFileTypes: true });

It needs callback