Node JS同步读取一行文本

时间:2019-03-05 03:46:48

标签: javascript node.js typescript

我有以下这种情况,其中我有data.txt,包含数千行。

我的目标是读取这些文件的每一行并提取一些数据并将其存储在数组中。我使用readlinefs.createReadStream

这就是我所做的:

const readingText = async () => {
  const fileStream = fs.createReadStream(
    "./data.txt"
  );

  const rl = readline.createInterface({
    input: fileStream,
    crlfDelay: Infinity
  });

  let dd = [];
  rl.on("line", line => {
    dd.push(line.split(":")[1]);
  });
  rl.on("close", async line => {
    console.log(dd);
    return dd;
  });
};

const someFunc = async () => {
  try {
    const ff = await readingText();
    console.log(ff);
  } catch (err) {
    console.log(err);
    return false;
  }
};

someFunc();

问题是console.log(ff)总是返回undefined,而console.log(dd)正确返回了所需的dd数组,为什么?以及如何使console.log(ff)等到ff变量分配给dd数组的值?

谢谢

1 个答案:

答案 0 :(得分:1)

基于事件的执行不会等待父异步函数。

尝试一下:

const readingText = async () => {
  return new Promise((resolve, reject) => {
    const fileStream = fs.createReadStream(
      "./data.txt"
    );

    const rl = readline.createInterface({
      input: fileStream,
      crlfDelay: Infinity
    });

    let dd = [];
    rl.on("line", line => {
      dd.push(line.split(":")[1]);
    });
    rl.on("close", line => {
      console.log(dd);
      return resolve(dd);
    });
  });

};

const someFunc = async () => {
  try {
    const ff = await readingText();
    console.log(ff);
  } catch (err) {
    console.log(err);
    return false;
  }
};

someFunc();