Streams are objects that let you read data from a source or write data to a destination continuously. In Node.js, you perform I/O operations almost instinctively – reading from or writing to files, making HTTP requests, etc. Behind the scenes, these are wrapped up within streams.
There are four fundamental types of streams in Node.js:
1. Readable: Permits read operation i.e., used for reading from the source.
2. Writable: Permits write operation i.e., used for writing to the destination.
3. Duplex: It’s both Readable and Writable.
4. Transform: It’s like duplex but we can modify or transform the data while it is being read or written.
Here is how to use them:
Creating a Readable Stream
```
//First, require the ‘fs’ module
var fs = require(‘fs’);
//Then, create a stream from a file
var readableStream = fs.createReadStream(‘file.txt’);
//Handle ‘data’ events, which are emitted when data is available to be read from the stream
readableStream.on(‘data’, function(chunk) {
console.log(chunk);
});
//Handle ‘end’ events, when no more data is available on the stream
readableStream.on(‘end’, function() {
console.log(‘No more data to read!’);
});
```
Creating a Writable Stream
```
//Again, require the ‘fs’ module
var fs = require(‘fs’);
//Then, create a stream to a file
var writableStream = fs.createWriteStream(‘file.txt’);
//Write data to the stream
writableStream.write(‘Hello, ‘);
writableStream.write(‘world!’);
//End, tells the stream that no more data will be written.
writableStream.end();
```
Creating a Duplex Stream
Duplex streams are both Readable and Writable. A good use case of the ‘Duplex’ stream is a http web server request
Here is a small example:
```
require(‘http’).createServer(function (req, res) {
req.pipe(res); // Echo request back to response
}).listen(8080);
```
Please note that the `createServer` function by default creates a ‘Duplex’ stream (i.e., the request from the client), returning both the request(req) and the response(res) objects.
This small server simply echoes back whatever it receives.