开发者

Nodejs and Streams - A detailed overview?

开发者 https://www.devze.com 2023-04-12 09:35 出处:网络
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

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!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号