node.js readline: "TypeError: rl is not iterable"

node.js readline: "TypeError: rl is not iterable"

当我尝试 运行 我的代码时出现此错误:

file:///C:/Users/rb03/Documents/Testing/connect.js:27
for (const line of rl) {
                   ^

TypeError: rl is not iterable
    at file:///C:/Users/rb03/Documents/Testing/connect.js:27:24
    at Connection.<anonymous> (C:\Users\rb03\Documents\Testing\node_modules\mysql2\lib\connection.js:777:13)
    at Object.onceWrapper (node:events:514:26)
    at Connection.emit (node:events:394:28)
    at ClientHandshake.<anonymous> (C:\Users\rb03\Documents\Testing\node_modules\mysql2\lib\connection.js:121:14)
    at ClientHandshake.emit (node:events:394:28)
    at ClientHandshake.execute (C:\Users\rb03\Documents\Testing\node_modules\mysql2\lib\commands\command.js:44:10)
    at Connection.handlePacket (C:\Users\rb03\Documents\Testing\node_modules\mysql2\lib\connection.js:456:32)
    at PacketParser.onPacket (C:\Users\rb03\Documents\Testing\node_modules\mysql2\lib\connection.js:85:12)
    at PacketParser.executeStart (C:\Users\rb03\Documents\Testing\node_modules\mysql2\lib\packet_parser.js:75:16)

我的代码如下:

connection.connect(function(err) {
    if (err) throw err;
    console.log('Connected!');

    const rl = readline.createInterface({ input: fs.createReadStream('./Logs/Outputs/split.lines.txt') });

    let total = 0;
    let buff = [];
    for (const line of rl) {
        buff.push([line]);
        total++;
        if (buff.length % 2000 === 0) {
            connection.query("INSERT INTO test (line, timestamp, errortype) VALUES ?");
            console.log(total);
            buff = [];
        };
    };

    if (buff.length > 0) {
        connection.query("INSERT INTO test (line, timestamp, errortype) VALUES ?");
        console.log(total);
    };

    connection.end();
});

有人知道该怎么做吗? Google 不显示“rl 不可迭代”,只显示“rl 不可异步迭代”

提前致谢!

如果你想为每行输入执行一个代码,你可以使用line事件。

rl.on('line', (input) => {
  console.log(`Received: ${input}`);
});

参见Readline documentation

编辑:有一个 asyncIterator symbol 可用于迭代 Readline.Interface。但是,它需要一个 for await...of 循环,而不是常规的 for...of 循环。

for await (const line of rl) {
  console.log(`Received: ${line}`);
}

要进行迭代,需要:

for await (const line of rl)

这需要在 async 函数中。您缺少 await.

rl 有一个 asyncIterator,但不是常规迭代器,因此您需要 await 才能使迭代工作。


如果不想迭代,可以使用常规事件,监听line事件

rl.on('line', line => {
   // process line here
});