Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node- Read the content of all files in a directory and directories inside that directory

My directory structure is as follows

|demo
  |abc
    abc.js
    abc.html
  |xyz
    test.js
    test.html
  |images
  pqr.js

I want to read the content of every file in the demo repository and its sub repositories. Need to match a pattern in every file and on a successful match, that entry should go into an array along with the filename. Any suggestions?

I tried the following code but it won't read the files inside the sub directories

var fs=require('fs');

var dir = './demo';
fs.readdir(dir,function(err,files){
  if (err) throw err;
  files.forEach(function(file){
    if(file) {
      fs.readFile('./demo/'+file, 'utf8', function (err,data) {
        if (err) {
          return console.log(err);
        }
        console.log(data);
      });
    }
  });
});

I don't want an array of directories. I want to read the content of every file in the directory and sub directories and match a string. If the string is present, enter it into an array with the filename.

like image 485
Nikita Jajodia Avatar asked Sep 11 '25 19:09

Nikita Jajodia


1 Answers

This chunk of code can do this very well, take a loop:

  let data = [];

  fs.readdirSync("absolute-directory", "utf8").forEach((file) => {
    data.push(fs.readFileSync("absolute-directory" + file, "utf8"));
  });

  return data;
}

like image 118
Md Abdul Halim Rafi Avatar answered Sep 13 '25 10:09

Md Abdul Halim Rafi