Home > Software design >  node.js readline: "TypeError: rl is not iterable"
node.js readline: "TypeError: rl is not iterable"

Time:09-22

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:\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)

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!

CodePudding user response:

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

CodePudding user response:

If you want to execute a code for each line of input, you can use the line event.

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

See the Readline documentation.

EDIT: There is an asyncIterator symbol that can be used to iterate over Readline.Interface. However, instead of a regular for...of loop, it requires an for await...of loop.

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