最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

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

IT培训 admin 5浏览 0评论

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

如何更改此代码:

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 ),很快就会达到堆的限制。

回答如下:

使用异步等待

(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();
      });
    })  
  }
})();

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

如何更改此代码:

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 ),很快就会达到堆的限制。

回答如下:

使用异步等待

(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();
      });
    })  
  }
})();
发布评论

评论列表 (0)

  1. 暂无评论