如何同步执行函数以获得正确的输出

How to execute functions synchronously to get the right output

我正在制作一个读取文件并逐行提取数据的应用程序。然后将每一行存储为一个数组元素,并且需要该数组作为最终输出。

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

var output_array=[];
const readInterface = readline.createInterface({
    input: fs.createReadStream(inp_file),
    console: false
});
readInterface.on('line', function(line) {
    //code for pushing lines into output_array after doing conditional formatting
}

callback (null, output_array);

有了这个,我得到了一个空数组。 虽然如果我使用 'setTimeout' 那么它工作正常

setTimeout(() => {
  callback (null, output_array);
}, 2000);

如何在不使用 'setTimeout' 的情况下同步执行此操作?

readline's close event 处理程序进行回调。这样你的回调将在所有行被读取后发生。

readInterface.on('close', function(line) {
  callback (null, output_array);
}

您不能同步执行异步函数。但是readline支持close事件,当输入文件完全读取时触发,所以你可以在那里调用回调。

readInterface.on('close', () => {
   callback(null, output_array);
});

当然你可以这样输出close event, but you could also use a promise上的内容:

function readFile(fileName) {
  return new Promise((resolve, reject) => {
      const readInterface = readline.createInterface({
        input: fs.createReadStream(fileName).on('error', error => {
          // Failed to create stream so reject.
          reject(error);
        }),
      });
      const output = [];
      readInterface.on('error', error => {
        // Some error occurred on stream so reject.
        reject(error);
      });
      readInterface.on('line', line => {
        output.push(line);
      });
      readInterface.on('close', () => {
        // Resolve the promise with the output.
        resolve(output);
      });
  });
}

readFile(inp_file)
  .then(response => {
    callback(null, response);
  })
  .catch(error => {
    // Take care of any errors.
  });

我在调用 createInterface() 时删除了 console 设置,因为它似乎不是有效的 option