Node JS Tutorial - Writable Streams

In this tutorial, we will learn about Writable Streams in Node.js. Streams provide an efficient way to handle reading and writing files, network communications, and end-to-end information exchange.

Writable Streams allow us to write data. Let's explore how to use Writable Streams in Node.js.

Using Writable Streams

Go to the project and open the index.js file. Require the http and fs packages:


var fs = require('http');
var fs = require('fs');
var readStream = fs.createReadStream(__dirname + '/message.txt','utf8');
var writeStream = fs.createWriteStream(__dirname + '/message2.txt');
readStream.on('data',function(chunk){
    console.log('new chunk recieved:');
    writeStream.write(chunk);
});

Now, run the code by going to the command prompt and executing the index.js file:


node index.js

Return to the project and you will see that a new file named message2 has been created. Inside this file, you will find the text that was written using the Writable Stream.

In this way, you can use Writable Streams in Node.js to efficiently write data to files or other destinations.