简体   繁体   English

Nodejs和Streams - 详细概述?

[英]Nodejs and Streams - A detailed overview?

Could anyone please explain to us (just me?) how to use Streams in Nodejs? 任何人都可以向我们解释(只是我?)如何在Nodejs中使用Streams?

This is a follow-up of this: Compression and decompression of data using zlib in Nodejs 这是对此的后续跟踪: 使用Nodejs中的zlib压缩和解压缩数据

And my main interest would be to work with files, but also strings (ie Stream.toString() and String.toStream()... not real function...) 我的主要兴趣是处理文件,还有字符串(即Stream.toString()和String.toStream()......不是真正的函数......)

Thanks! 谢谢!

A stream is an abstract interface implemented by various objects in Node. 流是由Node中的各种对象实现的抽象接口。 For example a request to an HTTP server is a stream, as is stdout. 例如,对HTTP服务器的请求是流,stdout也是如此。 Streams are readable, writable, or both. 流是可读的,可写的,或两者兼而有之。 All streams are instances of EventEmitter. 所有流都是EventEmitter的实例。 ( Streams Documentation ) Streams文档

This means a Stream is a useful object used by several Node core objects to read and/or write information. 这意味着Stream是几个Node核心对象用来读取和/或写入信息的有用对象。 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. 由于Stream是EventEmitter的一个实例,因此您的代码可以是异步的,并且在从某处读取信息时不会停顿。

// 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 . 检查stream.pipe

For example, to stream a video to an HTTP client while reading it from a file. 例如,在从文件读取视频时将视频流式传输到HTTP客户端。 Or stream an upload to a local file. 或者将上传流式传输到本地文件。 Use your imagination. 动用你的想象力。

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

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