5

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!

Community
  • 1
  • 1
Eli
  • 2,666
  • 7
  • 33
  • 37

1 Answers1

5

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.

dresende
  • 2,211
  • 1
  • 16
  • 25
  • That's what they meant by stating that something is the instance of EventEmitter i.e. they wanted to declare it's asynchronous ! When you read some stuff and you answer misc questions floating in you head for a while . I'll keep that one . Thanks @dresende – projektorius96 Sep 17 '21 at 22:19