如何手动实施背压

时间:2019-07-12 12:13:53

标签: node.js stream es6-promise child-process asynchronous-javascript

我有子进程,因为我正在将流传递给父进程。

在child.js中

  let stream = readdirp(pathname);
  stream.pipe.pipe(process.stdout);   

在parent.js中

let file = child => {
  let estream = es.map((data, next) => {
    _this.s3MultiUpload(JSON.parse(data), data, next);
    //i uploding this files to s3.
  });
  child.on("end", (code, signal) => {
    console.log("stream ended"); // `here is my problem`
    child.kill();
  });
  child.on("exit", (code, signal) => {
    console.log(code);
    console.log(signal);
    child.kill();
  });
  return estream;
};
child = fork(filePath, { silent: true });
child.stdout.pipe(this.file(child));

我的问题是在我将所有文件上传到s3流之前结束。我研究了背压,但是我不知道如何在此处实施?

我认为我需要添加回调或其他东西来处理stdout管道。我不知道

能帮我吗

1 个答案:

答案 0 :(得分:1)

该方法不必要地复杂。由于IO操作不受CPU限制,因此最好使用Promises以及JavaScript的async / await*语法来执行并行文件上传。建立我们自己的同步机制很复杂,并且出现了许多重叠的语言和库级别概念, 1

基于readdirp documentation,但是请注意我对特定的上载API的不熟悉,我建议遵循以下原则

const readdirp = require('readdirp');
const util = require('util');
const fs = require('fs');

const readfile = util.promisify(fs.readfile);

(async function () {
  // Use streams to achieve small RAM & CPU footprint.
  // 1) Streams example with for-await. Node.js 10+ only.
  const paths = [];
  for await (const {path} of readdirp('pending-uploads')) {
    paths.push(path);
  }

  const uploadPromises = paths
    .map(readFile)
    .map(JSON.parse).
    .map(data => s3MultiUpload(data));

  await Promise.all(uploadPromises);
}());

1 。背压是将Reactive Extensions库移植到以Java实现它的JVM的过程中之一。只是为了论证(理智?)考虑使用what Erik Meijer says regarding backpressure