Subject not found.
1.

Explain types of streams in Node.js?

Answer»

Streams are abstract interface available with Node.js.The stream module HELPS in implementation of streaming data. There are four TYPES of streams.

  • <Readable> for the reading operation
  • <Writable> for the writing operation
  • <Duplex> for both reading and writing operations
  • <Transform> is a derived from Duplex stream that computes available input.

The important events on a readable stream are:

  • The data EVENT, where the stream passes a chunk of data to the consumer.
  • The end event, which happens when there is no more data to be used from the stream.

For eg:

Reading a file “input.txt”

var fs = require('fs'); var readableStream = fs.createReadStream('input.txt'); // creates readable stream                  var data = ''; readableStream.on('data', function(txt) {    // data event produces the flow of data     data+=txt; }); readableStream.on('end', function()  // end event is triggered when no data to read {     console.log(data); });

The important events on a writable stream are:

  • The write event, that signals that the writable stream can receive more data.
  • The finish event, that is produced when all data has been written to the underlying system.

For eg:

Write “Hello World “ to file.txt

var fs = require("fs"); var data = 'Hello world'; var writerStream = fs.createWriteStream('file.txt');  // Create a writable stream writerStream.write(data,'UTF8'); // Write the data to stream  // Mark the end of file writerStream.end(); writerStream.on('finish', function() {  // finish triggered when all data is written to     console.log("Write completed."); });

PIPING the streams is one of the most popular mechanisms in Node.js programs where output of one stream is provided as the input to another stream.For eg:

var fs = require("fs"); var readerStream = fs.createReadStream('example.txt'); // Readable stream var writerStream = fs.createWriteStream('exampleOutput.txt'); // Writable stream readerStream.pipe(writerStream);// Pipe the readable stream as input to writable stream console.log("Program Ended");


Discussion

No Comment Found