InterviewSolution
Saved Bookmarks
| 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.
The important events on a readable stream are:
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:
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"); |
|