You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js使用readline时报TypeError: rl is not iterable如何解决

报错原因

readline.createInterface() 返回的实例不支持普通同步 for...of 遍历,仅支持异步迭代,所以直接使用同步遍历逻辑会触发rl is not iterable类型错误。另外你现有代码中SQL插入逻辑缺少参数传入,即使遍历问题解决也无法正常写入数据。

修复方案

方案1:异步迭代写法(Node.js v11.14.0及以上版本适用)

将外层回调改为异步函数,使用for await...of遍历rl实例,同时补全SQL插入参数:

const mysql = require('mysql2/promise'); // 推荐使用promise版本的mysql2方便async/await调用

connection.connect(async 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 await (const line of rl) {
        buff.push([line, Date.now(), 'your_error_type']); // 补全timestamp、errortype两个字段的实际值
        total++;
        if (buff.length % 2000 === 0) {
            // 补全插入参数
            await connection.query("INSERT INTO test (line, timestamp, errortype) VALUES ?", [buff]);
            console.log('已插入:', total);
            buff = [];
        };
    };

    if (buff.length > 0) {
        await connection.query("INSERT INTO test (line, timestamp, errortype) VALUES ?", [buff]);
        console.log('总插入数:', total);
    };

    connection.end();
});

方案2:事件监听写法(兼容所有Node.js版本)

如果你的Node.js版本较低不支持异步迭代,可以通过监听readline的事件实现逐行读取:

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 = [];

    // 监听逐行读取事件
    rl.on('line', (line) => {
        buff.push([line, Date.now(), 'your_error_type']);
        total++;
        if (buff.length % 2000 === 0) {
            connection.query("INSERT INTO test (line, timestamp, errortype) VALUES ?", [buff], (err) => {
                if (err) throw err;
                console.log('已插入:', total);
            });
            buff = [];
        }
    });

    // 监听读取完成事件
    rl.on('close', () => {
        if (buff.length > 0) {
            connection.query("INSERT INTO test (line, timestamp, errortype) VALUES ?", [buff], (err) => {
                if (err) throw err;
                console.log('总插入数:', total);
                connection.end();
            });
        } else {
            connection.end();
        }
    });

    // 监听错误事件
    rl.on('error', (err) => {
        throw err;
    });
});

内容的提问来源于stack exchange,提问作者mirairoses

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 13:36:03