Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs and Streams - A detailed overview?

Tags:

stream

node.js

Could anyone please explain to us (just me?) how to use Streams in Nodejs?

This is a follow-up of this: Compression and decompression of data using zlib in Nodejs

And my main interest would be to work with files, but also strings (i.e. Stream.toString() and String.toStream()... not real function...)

Thanks!

like image 925
Eli Avatar asked Oct 11 '11 11:10

Eli


1 Answers

A stream is an abstract interface implemented by various objects in Node. For example a request to an HTTP server is a stream, as is stdout. Streams are readable, writable, or both. All streams are instances of EventEmitter. (Streams Documentation)

This means a Stream is a useful object used by several Node core objects to read and/or write information. The core objects all use this to improve the way you can pipe information from one object to another. Since a Stream is an instance of an EventEmitter your code can be asynchronous and not stall while reading information from somewhere.

// imagine 'response' is the output Stream from a client connection
var video = fs.createReadStream("/path/to/video.mpg");
// pipe video to response (while data is being read asynchronously)
video.pipe(response);

Check stream.pipe.

For example, to stream a video to an HTTP client while reading it from a file. Or stream an upload to a local file. Use your imagination.

like image 179
dresende Avatar answered Sep 22 '22 00:09

dresende