node.js readline: “TypeError: rl is not iterable”

When I try to run my code I get this error:

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:Usersrb03DocumentsTestingnode_modulesmysql2libconnection.js:777:13)
    at Object.onceWrapper (node:events:514:26)
    at Connection.emit (node:events:394:28)
    at ClientHandshake.<anonymous> (C:Usersrb03DocumentsTestingnode_modulesmysql2libconnection.js:121:14)
    at ClientHandshake.emit (node:events:394:28)
    at ClientHandshake.execute (C:Usersrb03DocumentsTestingnode_modulesmysql2libcommandscommand.js:44:10)
    at Connection.handlePacket (C:Usersrb03DocumentsTestingnode_modulesmysql2libconnection.js:456:32)
    at PacketParser.onPacket (C:Usersrb03DocumentsTestingnode_modulesmysql2libconnection.js:85:12)
    at PacketParser.executeStart (C:Usersrb03DocumentsTestingnode_modulesmysql2libpacket_parser.js:75:16)

My code is as follows:

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();
});

Anyone got any idea what to do? Google shows nothing for “rl is not iterable”, only for “rl is not async iterable”

Thanks in advance!

Answer

To do iteration, it needs to be:

for await (const line of rl)

and this needs to be in an async function. You are missing the await.

rl has an asyncIterator, but not a regular iterator so you need the await to get the iteration to work.


If you don’t want to iterate, you can use regular events and listen for the line event.

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