Find your content:

Search form

Learn node.js simple way - Stream concepts - Code example write stream

 
Share

 

Create a file called "writestreamexample.js" and put the following code.

var fs = require("fs");
var data = 'Keep learning and make sure you are updated with trends.';

// Create a writable stream
var writerStream = fs.createWriteStream('write.txt');

// Write the data to stream with encoding to be utf8
writerStream.write(data,'UTF8');

// Mark the end of file
writerStream.end();

// Handle stream events --> finish, and error
writerStream.on('finish', function() {
console.log("Write completed.");
});

writerStream.on('error', function(err) {
console.log(err.stack);
});

console.log("Program Ended");

 

run this program

node writestreamexample.js

 

you see the below output in console.

Program ended
Write completed

 

Open a write.txt file and check the content.

My Block Status

My Block Content