简体   繁体   中英

Nodejs and Streams - A detailed overview?

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 (ie Stream.toString() and String.toStream()... not real function...)

Thanks!

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.

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