保存由readline模块制作的数组

问题描述 投票:0回答:1

我有下一段代码。这个函数必须返回一个基于txt文件的数组。问题是当我逐块打印数组时,它打印得很好。但是当我从接口中打印数组时,该数组为空。

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

function read_file(filename) {
   const filePath = './uploads/' + filename;
   var data = []

   data = readline.createInterface({
      input: fs.createReadStream(filePath),
      terminal: false
   }).on('line', function (
      data.push(line);
      console.log(data); // Here the array is filling well
   });

   console.log(data); // Buy here is empty again
}

javascript node.js readfile readline
1个回答
0
投票

这是由于Node.js的异步体系结构,您的console.log在读取文件任务之前执行。

如果您希望得到真实的结果,则必须使函数返回promise,并且还请注意,当事件结束时,请解析数据。

这样的事情可能会对您有所帮助:

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

async function read_file(filename) {
  const filePath = './uploads/' + filename;
  var readData = [];

  let data = await new Promise((resolve, reject) => {
    try {
      readline.createInterface({
        input: fs.createReadStream(filePath),
        terminal: false
      })
        .on('line', function (line) {
          readData.push(line);
        })
        .on('close', function() {
          resolve(readData);
        });
      }
      catch(e) {
       reject(e);
      }
   });

 console.log(data);
}
© www.soinside.com 2019 - 2024. All rights reserved.