Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Piping stream to a variable!? or ....?

What are my options to pipe stream to a variable? Based on this documentation the examples of writable stream include:

  • http requests, on the client
  • http responses, on the server fs write
  • streams zlib streams
  • crypto streams
  • tcp sockets
  • child process stdin
  • process.stdout, process.stderr

So does it mean I cannot pipe stream to a variable to process it? In fact I dont want to save the stream on my disk, so what is the best way to pipe all of the streams and use that data?

Thanks please let me know if you need more clarification!


1 Answers

You probably can pipe a stream to a variable, but pipe is generally used to pipe the stream to some other method that can utilize the stream, as pipe pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream.

For instance, piping a stream to a file

someReadableStream.pipe(fs.createWriteStream("result.json"));

If you just want the data in a variable, there are events for that, that are probably easier to use, like on('data')

var readable = getReadableStreamSomehow(),
    result   = '';

readable.on('data', function(chunk) {
      result += chunk;
});

readable.on('end', function () {
    // do something with "result"
});
like image 87
adeneo Avatar answered Dec 30 '25 08:12

adeneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!