Pipe streams
Pipe is mechanism which works in a way that output of one stream would be input of other stream. It is chaining executions. Create a file called "pipe.js"
var fs = require("fs");
// Create a readable stream
var readerStream = fs.createReadStream('test.txt');
// Create a writable stream
var writerStream = fs.createWriteStream('output.txt');
// Pipe the read and write operations
// read test.txt and write data to output.txt
readerStream.pipe(writerStream);
console.log("Program Ended");
Run the program.
node pipe.js
Check the output.txt file.
Chaining the Streams
Chaining is a mechanism to get the output of one stream to another stream and create a chain of multiple stream operations.
In the below example, we read the file and create a zip and write the content into zip file.
var fs = require("fs");
var zlib = require('zlib');
// Compress the file input.txt to input.txt.gz
fs.createReadStream('test.txt')
.pipe(zlib.createGzip())
.pipe(fs.createWriteStream('test.txt.gz'));
console.log("File Compressed.");
Run the program and check the output.
Decompress the file
var fs = require("fs");
var zlib = require('zlib');
// Decompress the file input.txt.gz to input.txt
fs.createReadStream('test.txt.gz')
.pipe(zlib.createGunzip())
.pipe(fs.createWriteStream('test.txt'));
console.log("File Decompressed.");
Run the program and check the output.