0

the line "node jsfile.js txt mama" should result in finding all files with the .txt extension and which contain the string "some".

I've tried this which works pretty good but have a little bug - if mia.txt and mama.txt files have the string "some" it prints mia.txt, mia.txt instead of printing mama.txt, mia.txt

JAVSCRIPT CODE:

/* Sending error if command line arguments is not exactly 4 */

if (process.argv.length != 4) {
    console.log("USAGE: node " + process.argv[1] + " [EXT ] [TEXT].");
    /* TODO:error message and quit program*/
}

/* Declarations: */

var fs = require('fs');
var path = require('path');
var dirPath = path.resolve(__dirname);
var files = fs.readdirSync(dirPath);
var requestedExtension = "." + process.argv[2];
var requestedString = process.argv[3];
var amountOfMatchingFiles = 0;
var resultListOfMatchingFiles = "";
var extensionFilter = [];

/* Retrieving all files with the requested file extension filter: */

for(var i in files) {
    if(path.extname(files[i]) === requestedExtension) {
        extensionFilter.push(files[i]);
    }
}
console.log("after file extension filter:" + extensionFilter);

/* Retrieving all files with the requested file extension filter and requested string: */

for(var i in extensionFilter) {
    var fullFilePath = dirPath + "\\" + extensionFilter[i];
    fs.readFile(fullFilePath, function (err, data) {
            if (err) throw err;
            if(data.indexOf(process.argv[3]) >= 0) {
            console.log(extensionFilter[i]);
            amountOfMatchingFiles++;
            }
    });
}


/*
console.log(":::"+amountOfMatchingFiles);
if (amountOfMatchingFiles === 0)
{    
    console.log("No File Was Found" + amountOfMatchingFiles);
}*/

1 Answers1

1

This is a classic JavaScript problem and it's in your last for loop:

for (var i in extensionFilter) {
  var fullFilePath = dirPath + "\\" + extensionFilter[i];
  fs.readFile(fullFilePath, function (err, data) {
    if (err) throw err;
    if (data.indexOf(process.argv[3]) >= 0) {
      // HERE extensionFilter[i] is "mia.txt" since i has reached
      // it's last value
      console.log(extensionFilter[i]);
      amountOfMatchingFiles++;
    }
  });
}

Use a .forEach() instead

extensionFilter.forEach(function (filter) {
  var fullFilePath = dirPath + "\\" + filter;
  fs.readFile(fullFilePath, function (err, data) {
    if (err) throw err
    if (data.indexOf(process.argv[3]) >= 0) {
      console.log(filter);
      amountOfMatchingFiles++
    }
  })
})
rtn
  • 127,556
  • 20
  • 111
  • 121
  • And that's why you answer without any explanation on the underlying problem, instead of voting to closing with a duplicate with a proper explanation... – Andreas Mar 15 '18 at 11:22