简体   繁体   English

Node.js-将可写流分配给变量

[英]Node.js - assign writable stream to a variable

As in below code, I can write base64 encoded stream into a file but I want to assign the base64 encoded string to a variable rather than creating a file so that I can use it for the purpose I want. 如下面的代码所示,我可以将base64编码的流写入文件,但是我想将base64编码的字符串分配给变量,而不是创建文件,以便可以将其用于所需的目的。 How can I assign response.pipe(base64.encode()); 如何分配response.pipe(base64.encode()); to a variable as base64 encoded string ? 到一个变量作为base64编码的字符串? I am using base64-stream to encode incoming stream. 我正在使用base64-stream编码传入流。

const request = xero.call('GET', `/Invoices/${invoiceId}`);
  request.setHeader('Accept', 'application/pdf');

  request.on('response', async (response) => {
    const data = response.pipe(base64.encode());
    const file = fs.createWriteStream(`${invoiceId}.txt`);
    data.pipe(file);
  });
  request.end();

To store the contents of the stream as a string you need to concatenate the base64 stream and then store that buffer as a variable. 要将流的内容存储为字符串,需要连接base64流,然后将该缓冲区存储为变量。 For that I like to use concat-stream . 为此,我喜欢使用concat-stream

keep the stream around with const data = response.pipe(base64.encode()); const data = response.pipe(base64.encode());保持流const data = response.pipe(base64.encode());

but then 但是之后

data.pipe(concat(buf => {
  const str = buf.toString('base64')
})

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

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