Tony
Tony

Reputation: 494

fs.readdir and fs.readfile and regex

This is a Node application, running express server. I have a folder with text files in it. I need to be able to go into each one of those files inside the folder, and extract lines that include a word "SAVE".

I am stuck at this step.

app.get('/logJson', function (req, res) {
  const logsFolder = 'C:/logs/';
  fs.readdir(logsFolder, (err, files) => {
    if (err) {
      res.send("[empty]");
      return;
    }
    files.forEach(function(filename){
      var logFiles = fs.readFileSync (logsFolder + filename, 'ascii').toString().split("\n");
      console.log(logFiles + "\n");
    })
  })
})

I cannot figure out where do I include this:

var log = (logFiles.split(/.*SAVE.*/g)||['no result found'])[0];

Any help would be appreciated

Upvotes: 1

Views: 5897

Answers (1)

ssc-hrep3
ssc-hrep3

Reputation: 16089

If you only want to print out all lines containing the word SAVE, you could do it like this.

Remark: I did not run this code.

app.get('/logJson', function (req, res) {
  const logsFolder = 'C:/logs/';
  fs.readdir(logsFolder, (err, files) => {
    if (err) {
      res.send("[empty]");
      return;
    }
    var lines = [];
    files.forEach(function(filename) {
      var logFileLines = fs.readFileSync (logsFolder + filename, 'ascii').toString().split("\n");

      // go through the list of logFileLines
      logFileLines.forEach(function(logFileLine) {

        // if the current line matches SAVE, it will be stored in the variable lines
        if(logFileLine.match(/SAVE/)) {
          lines.push(logFileLine);
        }
      })
    })

    // the variable lines is printed to the console
    console.log(lines);
  })
})

Upvotes: 1

Related Questions