Streams are instances of EventEmitter which can be used to work with streaming data in Node.js
There are mainly four types of the stream:
Writable:
fs.createWriteStream()
Readable:
fs.createReadStream()
Duplex: (Both Readable and Writable)
net.Socket
Transform: Duplex streams that can modify or transform the data as it is written and read
zlib.createDeflate()
Buffers
Buffers is a temporary memory that is mainly used by stream to hold on to some data until consumed.
// Nodejs Buffervar buf = new Buffer('Hello', 'utf8'); // size is fixed with initial value as Helloconsole.log(buf.toString()); // Hellobuf.write('wo');console.log(buf.toString()); // wollo
ES6 has defined ArrayBuffer which is the way of dealing with Buffers in core javascript itself
Common use case is to read from one stream and write to another stream, copy contents of one file to another for example:
const fs = require('fs');const readableStream = fs.createReadStream(__dirname + '/input.txt');const writableStream = fs.createWriteStream(__dirname + '/output.txt');readableStream.pipe(writableStream); // will copy contents of input.txt to output.txt// Alternatively without pipes the code will be the following:readableStream.on('data', function(chunk) { writableStream.write(chunk);});