How to fix this code in TypeScript (ES5+) such that the callback function of readInterface.on()
can access the lines
array declared outside the function?
const readline = require('readline');
const fs = require('fs');
const readInterface = readline.createInterface({
input: fs.createReadStream("data.list"),
output: false,
silent: true,
console: false
});
var lines: string[] = [];
readInterface.on('line', function(line) {
if (line && line.indexOf("#") !== 0) {
this.lines.push(line);
}
});
lines.forEach(line => {
console.log(line);
});
Edit:
The solution
In fact this question posed to problems to tackle. The first error was resolved by @Andreas by outlining that the this
keyword should be removed from the line this.lines.push(line);
The desired outcome of the question, however, was to synchronously return the lines read by the asynchronous function readInterface.on('line', function(line) { ... });
, with the misunderstanding that the function was actually synchronous.
The solution was to use the synchronous alternative readlinesSync
from a package available on npm as readlines.
const readlines = require('readlines');
var _lines: string[] = readlines.readlinesSync('dat/test.list');
var lines: string[] = [];
_lines.forEach(line => {
if (line && line.indexOf("#") !== 0) {
lines.push(line);
}
});
lines.forEach(line => {
console.log(line);
});