DEV Community

Rahul kumar
Rahul kumar

Posted on

Read nested files too in NodeJs

import fs from "fs";

// preset -> base path + new path
function readFiles(preset, paths, files) {
    paths.forEach(path => {
        if (fs.lstatSync(preset + path).isFile()) {
            files.push(preset + path);
        } else {
            const dirs = fs.readdirSync(preset + path);
            readFiles(preset + path + "/", dirs, files);
        }
    });
}

// base -> base path
function readAllFiles(base) {
    const files = [];
    const dirs = fs.readdirSync(base);
    readFiles(base, dirs, files);
    return files;
}

// read files
const files = readAllFiles("./");

// print files
files.forEach(file=>{
    const content = fs.readFileSync(file,{encoding:"utf-8"});
    console.log({
        [file]:content
    })
})
Enter fullscreen mode Exit fullscreen mode

Top comments (0)