What is piping and chaining in Node.js?
Piping the Streams
Piping is a mechanism where we provide the output of one stream as the input to another stream. It is normally used to get data from one stream and to pass the output of that stream to another stream. There is no limit on piping operations. Now we'll show a piping example for reading from one file and writing it to another file.
Create a js file named main.js with the following code −
var fs = require("fs"); // Create a readable stream var readerStream = fs.createReadStream('input.txt'); // Create a writable stream var writerStream = fs.createWriteStream('output.txt'); // Pipe the read and write operations // read input.txt and write data to output.txt readerStream.pipe(writerStream); console.log("Program Ended");
Now run the main.js to see the result −
$ node main.js
Verify the Output.
Program Ended
Open output.txt created in your current directory; it should contain the following −
Tutorials Point is giving self learning content to teach the world in simple and easy way!!!!!
Chaining the Streams
Chaining is a mechanism to connect the output of one stream to another stream and create a chain of multiple stream operations. It is normally used with piping operations. Now we'll use piping and chaining to first compress a file and then decompress the same.
Create a js file named main.js with the following code −
var fs = require("fs"); var zlib = require('zlib'); // Compress the file input.txt to input.txt.gz fs.createReadStream('input.txt') .pipe(zlib.createGzip()) .pipe(fs.createWriteStream('input.txt.gz')); console.log("File Compressed.");
Now run the main.js to see the result −
$ node main.js
Verify the Output.
File Compressed.
You will find that input.txt has been compressed and it created a file input.txt.gz in the current directory. Now let's try to decompress the same file using the following code −
var fs = require("fs"); var zlib = require('zlib'); // Decompress the file input.txt.gz to input.txt fs.createReadStream('input.txt.gz') .pipe(zlib.createGunzip()) .pipe(fs.createWriteStream('input.txt')); console.log("File Decompressed.");
Now run the main.js to see the result −
$ node main.js
Verify the Output.
File Decompressed.
Comments
Post a Comment