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

使用readline读取文件时,如何通过async/await正确获取结果?

Node.js readline读取文件时异步逻辑等待问题

你的代码里readTwoColumnFile是异步函数,但内部并没有返回一个能被await等待的Promise,导致run函数里的await直接跳过,拿到undefined,输出顺序不符合预期。

原代码

const fs = require('fs');
const rl = require("readline");

async function readTwoColumnFile() {

    console.log('reading file');

    // (C) READ LINE-BY-LINE INTO ARRAY
    const reader = rl.createInterface({
      input: fs.createReadStream("index.js")
    });

    reader.on("line", (row) => {
      //some code
    });

    // (D) DONE - FULL ARRAY
    reader.on("close", async () => {
      // some code
      console.log('reading complete')
      res = 'Hello World!'
      return res
    });
}

async function run(){
    const res = await readTwoColumnFile()
    console.log('data' , res)
}

run()

当前输出

reading file
data undefined
reading complete

期望输出

reading file
reading complete
data Hello World!

解决方案

要让await能等待文件读取完成,需要把readTwoColumnFile内部的readline事件逻辑包裹在Promise中,在close事件触发时通过resolve返回结果,同时处理error事件避免Promise一直处于pending状态:

修改后的代码:

const fs = require('fs');
const rl = require("readline");

function readTwoColumnFile() {
    // 用Promise包裹异步逻辑
    return new Promise((resolve, reject) => {
        console.log('reading file');

        const reader = rl.createInterface({
            input: fs.createReadStream("index.js")
        });

        reader.on("line", (row) => {
            // 处理每行数据的逻辑
        });

        reader.on("close", () => {
            console.log('reading complete')
            const res = 'Hello World!'
            resolve(res) // 读取完成后返回结果
        });

        // 处理文件读取错误
        reader.on("error", (err) => {
            reject(err)
        });
    });
}

async function run(){
    try {
        const res = await readTwoColumnFile()
        console.log('data' , res)
    } catch (err) {
        console.error('读取文件出错:', err)
    }
}

run()

关键改动说明

  1. 把readTwoColumnFile改为返回Promise(不需要加async,因为Promise本身就是异步容器)
  2. 在close事件中调用resolve(res),将结果传递给外部的await
  3. 添加error事件监听,用reject抛出错误,避免Promise挂起
  4. run函数中添加try/catch处理可能的读取错误

这样修改后,await readTwoColumnFile()会等待文件读取完成(close事件触发)后才继续执行,输出顺序就符合预期了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 18:35:13