I have blow code to read a text file line by line but it complains about an error on the for loop
. Type 'Interface' must have a '[Symbol.asyncIterator]()' method that returns an async iterator.ts(2504)
It seems relating to the rl
interface created from readline.createInterface
.
const fileStream = fs.createReadStream('test.text');
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity,
});
for await (const line of rl) {
...
CodePudding user response:
The simplest way to read the stream is to use rl.on('line', callback)
function onLine(line) {
console.log(line);
}
rl.on('line', onLine);
https://stackblitz.com/edit/node-her3vv?file=index.js
for await
should work provided it is inside of an async
function and your node version is greater than 11.14: https://nodejs.org/api/readline.html#rlsymbolasynciterator
async function readLines() {
for await (const line of rl) {
console.log(line);
}
}
readLines();