streams and Buffer in nodeJs | Readable and Writable streams

 NodeJS Streams

            Streams are objects that let you read data from a source or write data to a destination in continuous fashion. In Node JS, there are four types of streams.

        Streaming means listening to music or watching video in 'real time', instead of downloading a file to your computer and watching it later.

Readable stream which is used for read operation.
Writeable Stream which is used for write operation
Duplex Stream which can be used for both read and write operation
Transform A type of duplex stream where the output is computed based on input

Each type of Stream is on EventEmitter instanceand throws several events at different instance of times. For Example, some of the commonly used events are-
data This event is fired when there is data is availabe to read.
end This event is fired when there is no more data to read
error This event is fired whenn there is any error receiving or writing data
finish This event is fired when all the data has been flushed to underlying system
Normal Method .
const fs = require('fs');
const http = require('http')
const server = http.createServer();

server.on('request',(req, res)=>{
    fs.readFile("index.txt",(err, data)=>{
        if (err) return console.error(err);
        // console.log(data.toString());
        res.end(data.toString());
    });
});

server.listen(8000, "127.0.0.1");
Output

Streaming Method
const fs = require('fs');
const http = require('http')
const server = http.createServer();

server.on('request',(req, res)=>{
    const rstream = fs.createReadStream('index.txt');
    rstream.on('data',(chunkData)=>{
        res.write(chunkData);
    })
    rstream.on('end',()=>{
        res.end();
    });
    rstream.on('error',(err)=>{
        console.log(err);
    })
});

server.listen(8000, "127.0.0.1");
Output