home PYTHONJAVA
 

Node.js Streams


Streams are the items that facilitate you to read data from a source and compose data to a goal. There are four kinds of streams in Node.js:

  • Readable: This stream is utilized for read operations.
  • Writable: This stream is utilized for compose operations.
  • Duplex: This stream can be utilized for both read and compose operations.
  • Transform: It is sort of duplex stream where the yield is figured by input.

Each sort of stream is an Event emitter example and throws several events at various occasions. Following are some generally utilized events:

  • Data:This event is terminated when there is data accessible to read.
  • End:This event is terminated when there is no more data accessible to read.
  • Error: This event is terminated when there is any blunder getting or composing data.
  • Finish:This event is terminated when the sum total of what data has been flushed to fundamental system.

Node.js Reading from stream

Create a text file named input.txt having the following content:

  1. welookups is a one of the best online tutorial website to learn different technologies in a very easy and efficient manner.   

Create a JavaScript file named main.js having the following code:

File: main.js

  1. var fs = require("fs");  
  2. var data = '';  
  3. // Create a readable stream  
  4. var readerStream = fs.createReadStream('input.txt');  
  5. // Set the encoding to be utf8.   
  6. readerStream.setEncoding('UTF8');  
  7. // Handle stream events --> data, end, and error  
  8. readerStream.on('data', function(chunk) {  
  9.    data += chunk;  
  10. });  
  11. readerStream.on('end',function(){  
  12.    console.log(data);  
  13. });  
  14. readerStream.on('error', function(err){  
  15.    console.log(err.stack);  
  16. });  
  17. console.log("Program Ended");  

Now, open the Node.js command prompt and run the main.js

  1. node main.js  

Create a JavaScript file named main.js having the following code:

File: main.js

  1. var fs = require("fs");  
  2. var data = 'A Solution of all Technology';  
  3. // Create a writable stream  
  4. var writerStream = fs.createWriteStream('output.txt');  
  5. // Write the data to stream with encoding to be utf8  
  6. writerStream.write(data,'UTF8');  
  7. // Mark the end of file  
  8. writerStream.end();  
  9. // Handle stream events --> finish, and error  
  10. writerStream.on('finish', function() {  
  11.     console.log("Write completed.");  
  12. });  
  13. writerStream.on('error', function(err){  
  14.    console.log(err.stack);  
  15. });  
  16. console.log("Program Ended");  

Now open the Node.js command prompt and run the main.js

  1. node main.js  





welookups is optimized for learning.© welookups. 2018 - 2019 All Right Reserved and you agree to have read and accepted our term and condition.