Node JS Tutorial - Piping the Streams
In this tutorial, we will learn about piping streams in Node.js. Piping is a mechanism that allows us to provide the output of one stream as the input to another stream.
This technique is commonly used to retrieve data from one stream and pass the output to another stream for further processing. One of the key benefits of piping is that there is no limit to the number of piping operations that can be performed.
Piping Example: Reading from One File and Writing to Another
Let's take a look at an example of piping in action. We will read data from one file and write it to another file:
var fs = require("fs");
var readStream = fs.createReadStream(__dirname + '/message.txt','utf8');
var writeStream = fs.createWriteStream(__dirname + '/message3.txt');
readerStream.pipe(writerStream);
console.log("Program Ended");
Now, let's run the code. Go to the command prompt and execute the index.js file:
node index.js
Return to the project and you will see that a new file has been created. Open the file and you will find that it contains the same content as the original file.
In this way, you can use piping to efficiently process data from one stream and pass it to another stream in Node.js.