1

I have this code below. Using the readline and fs module I am trying to search for a particular word in a file line by line and if that word exist push the contents of that word to an array but when I try to return this array I get an undefined. Any ideas?

var fs = require('fs');
var readline  = require('readline');

var reader = readline.createInterface({
    input: fs.createReadStream('MY_FILE_NAME.txt'),
});

function newDefineWord(reader1) {
  this.reader = reader1;
}



newDefineWord.prototype.define = function(searchTerm) {
      var arr = [];

      this.reader.on('line', function (line) {
          if (line.search(searchTerm)!== -1) {            
            arr.push(line);
            console.log(arr);
          }
      });

      return arr;

}

var word = new newDefineWord(reader);
console.log(word.define('libro'));
1
  • 1
    I'm not a node expert but the way JS works which seems like the return arr is being retuened before the function gets executed, it's async, right? Check this. Commented Feb 7, 2016 at 23:33

1 Answer 1

1

reader.on is async you are returning it before the conclusion your code should be

    newDefineWord.prototype.define = function(searchTerm, cb) {
          var arr = [];
          this.reader.on('line', function (line) {

              if (line.search(searchTerm)!== -1) {            
                arr.push(line);
                console.log(arr);
              }
        });
        this.reader.on('close',function(){
            cb(arr)
        })

    }

    var word = new newDefineWord(reader);
    word.define('libro', function(arr){
        console.log(arr);

    })

Additionally if you do not want to use callbacks you can use promises or generators

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks will take a look at promises and emitters also, currently learning a lot at the moment just from this small exercise

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.