如何使用Node的流编写器保证执行顺序?

时间:2019-09-25 16:21:48

标签: javascript node.js streamwriter

如何更改此代码:

const fs = require('fs');

let list = ['a', 'b', 'c'];
list.forEach(x => {
  console.log('processing ' + x);
  let out_path = x + '.txt';
  let writeStream = fs.createWriteStream(out_path);
  writeStream.write('a lot of stuff will go here', 'utf8');
  writeStream.on('finish', () => {
    console.log(out_path + ' saved');
  });
  writeStream.end();
});

获取此信息:

processing a
a.txt saved
processing b
b.txt saved
processing c
c.txt saved

代替此:

processing a
processing b
processing c
a.txt saved
b.txt saved
c.txt saved

如果我在forEach循环中创建一个对象,然后使用fs.writeFile将每个对象写入文件,则效果很好...但是我无法做到这一点,因为我正在写大量数据量(GB)并很快达到堆的限制。

1 个答案:

答案 0 :(得分:0)

使用异步等待

(async () => {
  const fs = require('fs');

  let list = ['a', 'b', 'c'];
  for (let x of list) {
    console.log('processing ' + x);
    let out_path = x + '.txt';
    let writeStream = fs.createWriteStream(out_path);
    writeStream.write('a lot of stuff will go here', 'utf8');
    writeStream.end();
    await new Promise(resolve => {
      writeStream.on('finish', () => {
        console.log(out_path + ' saved');
        resolve();
      });
    })  
  }
})();