NodeJS 如何从'readline.createInterface'方法中循环一行?

4si2a6ki  于 2022-11-29  发布在  Node.js
关注(0)|答案(1)|浏览(144)

我已经吹代码逐行读取文本文件,但它抱怨关于for loop的错误。Type 'Interface' must have a '[Symbol.asyncIterator]()' method that returns an async iterator.ts(2504)
它似乎与从readline.createInterface创建的rl接口有关。

const fileStream = fs.createReadStream('test.text');

  const rl = readline.createInterface({
    input: fileStream,
    crlfDelay: Infinity,
  });

  for await (const line of rl) {
   ...
ca1c2owp

ca1c2owp1#

读取流的最简单方法是使用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位于async函数内部,并且节点版本高于11.14,则for await应该可以工作:https://nodejs.org/api/readline.html#rlsymbolasynciterator

async function readLines() {
  for await (const line of rl) {
    console.log(line);
  }
}

readLines();

https://stackblitz.com/edit/node-rquour?file=index.js

相关问题