javascript - Getting undefined node.js code -
i have code below. using readline
, fs
module trying search particular word in file line line , if word exist push contents of word array when try return array undefined. 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'));
reader.on async returning before conclusion code should
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 not want use callbacks can use promises or generators
Comments
Post a Comment