繁体   English   中英

获取未定义的node.js代码

[英]Getting undefined node.js code

我下面有这段代码。 使用readlinefs模块,我试图逐行搜索文件中的特定单词,如果该单词存在,则将该单词的内容推入数组,但是当我尝试返回此数组时,我得到的是不确定的。 有任何想法吗?

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'));

reader.on是异步的,您将在得出结论之前将其返回

    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);

    })

此外,如果您不想使用回调,则可以使用Promise或Generators

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM