简体   繁体   English

当一个 stream 依赖于另一个时,如何处理 node.js 流的情况?

[英]How to handle situation with node.js streams when one stream is dependant on another one?

I am developing a functionality for bulk uploading and I came with this issue.我正在开发批量上传的功能,我遇到了这个问题。

I want to archive files and that will be uploaded to my server.我想存档文件并将其上传到我的服务器。 Also the archive will contain a manifest file - which will describe each file with various properties / meta data / etc.此外,存档将包含一个清单文件 - 它将描述具有各种属性/元数据/等的每个文件。

The issue occurs when I want to send back the response.当我想发回响应时会出现问题。 The stream which is reading the manifest file is closed which leads to immediate callback execution.正在读取清单文件的 stream 已关闭,从而导致立即执行回调。 Bellow I will show the examples.下面我将展示示例。

const csv = require("fast-csv");
const fs = require("fs");
const path = require("path");

async function proccesUpload() {
  const manifestReadStream = fs.createReadStream(
    path.join(__dirname, "manifest.txt")
  );

  manifestReadStream
    .pipe(
      csv.parse({
        delimiter: ";",
      })
    )
    .on("data", async (row) => {
        // do processing for each file described in manifest file
      const hash = crypto.createHash("sha1");
      const rs = fs.createReadStream(targetFile, {
        flags: "r",
        autoClose: true,
      });
      rs.on("data", (data) => hash.update(data, "utf-8"));
      rs.on("close", function onReadStreamClose() {
        // do proccessing for file
      });
    })
    .on("end", async () => {
      // return response when all formating was performed
    });
}

By using nest read stream, the on "end" is executed before all the files are processed.通过使用嵌套读取 stream,在处理所有文件之前执行“结束”。 How can I solve this?我该如何解决这个问题?

I recommend using async iterators will make the code easier and callback free我建议使用异步迭代器将使代码更容易并且无需回调

async function proccesUpload() {
  const manifestReadStream = fs.createReadStream(
    path.join(__dirname, "manifest.txt")
  );

  const parserStream = manifestReadStream.pipe(
    csv.parse({
      delimiter: ";",
    })
  );

  for await (const row of parserStream) {
    // do processing for each file described in manifest file
    const hash = crypto.createHash("sha1");
    const rs = fs.createReadStream(targetFile, {
      flags: "r",
      autoClose: true,
    });
    for await (const data of rs) {
      hash.update(data, "utf-8");
    }
    // DONE PROCESSING THE ROW
  }

  // DONE PROCESSING ALL FILES
  // return response when all formating was performed
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM