0

How come count is always 0 even though there are words in the file that match the word to be found?

getWordCount (wordToFind, files) {
        var count = 0;
        for (let i in files) {
            FS.readFile(files[i], 'utf8', function (err, data) {
                data.split(/\s+/).forEach(function (word) {
                    if (word == wordToFind) {
                        count = count + 1;
                    }
                });
            });
        }
        console.log('Word Count for word: ' + wordToFind + ' is: ' + count);
Daljeet Virdi
  • 601
  • 1
  • 6
  • 10
  • I remember seeing an exact duplicate of this not to long ago, but I'm having trouble finding it now. However the problem is that you call `console.log` *before* the `FS.readFile` callback function is called. – Some programmer dude Oct 18 '16 at 07:53
  • FS.readFile is asynchronous. See here: http://stackoverflow.com/questions/10058814/get-data-from-fs-readfile So your console.log is most likely executed before the readFile function is ready. – antesoles Oct 18 '16 at 07:54

0 Answers0