简体   繁体   中英

How make transfer stream in node.js?

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...

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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