如何在node.js中传输流?

时间:2021-08-23 02:33:11

I use JsZip and exceljs packages. ExcelJs can write excel doc to node.js stream, jszip can read file from stream and add it to archive. How I can make stream-transfer between it for convenient working with it? I make this solution, but I think its bad crutch...

我使用JsZip和exceljs包。 ExcelJs可以将excel doc写入node.js流,jszip可以从流中读取文件并将其添加到存档中。我如何在它之间进行流传输以方便使用它?我做了这个解决方案,但我认为它的坏拐杖......

const stream2 = new Writable();
  stream2.result = [];
  stream2._write = function (chunk, enc, next) {
  this.result.push(chunk);
  next();
 };

  const stream1 = new Readable();
  stream1._read = function () {
    stream1.push(stream2.result.shift() || null);
  };

  let promise = new Promise((resolve, reject) => {
    excelDoc.write(stream2).then(() => {
      zip.file('excelDoc.xlsx', stream1);
      resolve(true);
    });
  });

1 个解决方案

#1


0  

I don't quite get what you're trying to do, but it seems like you are reinventing a Duplex Stream or Transform Stream. These are streams that are both Readable and Writable.

我不太了解你想要做的事情,但似乎你正在重新发明一个双工流或转换流。这些是可读和可写的流。

Transform streams are Duplex streams where the output is in some way related to the input, and we can use them to what you are trying to do (I think):

转换流是双工流,其输出在某种程度上与输入相关,我们可以将它们用于您尝试做的事情(我认为):

const stream = require('stream');

const transformStream = new stream.Transform({
  transform: (data, encoding, callback) => callback(null, data)
});

let promise = new Promise((resolve, reject) => {
  excelDoc.write(transformStream).then(() => {
    zip.file('excelDoc.xlsx', transformStream);
    resolve(true);
  });
});

Side note: normally you would do something like:

旁注:通常你会这样做:

inputStream.pipe(excelDoc).pipe(zipStream).pipe(outputStream);

But I see that neither of your dependencies support such syntax.

但我发现你的依赖关系都不支持这样的语法。

#1


0  

I don't quite get what you're trying to do, but it seems like you are reinventing a Duplex Stream or Transform Stream. These are streams that are both Readable and Writable.

我不太了解你想要做的事情,但似乎你正在重新发明一个双工流或转换流。这些是可读和可写的流。

Transform streams are Duplex streams where the output is in some way related to the input, and we can use them to what you are trying to do (I think):

转换流是双工流,其输出在某种程度上与输入相关,我们可以将它们用于您尝试做的事情(我认为):

const stream = require('stream');

const transformStream = new stream.Transform({
  transform: (data, encoding, callback) => callback(null, data)
});

let promise = new Promise((resolve, reject) => {
  excelDoc.write(transformStream).then(() => {
    zip.file('excelDoc.xlsx', transformStream);
    resolve(true);
  });
});

Side note: normally you would do something like:

旁注:通常你会这样做:

inputStream.pipe(excelDoc).pipe(zipStream).pipe(outputStream);

But I see that neither of your dependencies support such syntax.

但我发现你的依赖关系都不支持这样的语法。