Pipeline stream inputs data from one stream into another. learning points:
Read data from the stream
Write stream
Pipeline Flow
Chained stream
Node. js Stream (Stream)
Read data from the stream
Case: main. js
[Code] var fs = require ('fs'); var data = ''; // create a readable stream var readerStream = fs.createReadStream('input.txt '); // set utf8 encoding readerStream. setEncoding ('utf8'); // Process Stream events // trigger readerStream when data is readable. on ('data', function (chunk) {data + = chunk;}); // end triggers readerStream when no data is read. on ('end', function () {console. log (data) ;}); // error is triggered when an error occurs during receiving and writing. ReaderStream. on ('error', function (err) {console. log (err. stack) ;}); console. log ('program execution is complete. ');
Case: main2.js
[Code] var fs = require ('fs'); var data = 'Who am I? '; // Create the write stream var writeStream = fs.createWriteStream('ouput.txt'); // encode writeStream. write (data, 'utf8'); // mark the writeStream at the end of the file. end (); // triggered when stream event processing // finish all data has been written to the final level system. WriteStream. on ('finish ', function () {console. log ('write finished ') ;}); // error reading and writing data triggers writeStream. on ('error', function (err) {console. log (err. stack) ;}); console. log ('program execution is complete. ');
Case: pipe. js
[Code] var fs = require ('fs'); // create a readable stream var readerStream = fs.createReadStream('input.txt '); // create a write stream var writeStream = fs.createWriteStream('ouput.txt '); // read and write the readerStream In the MPs queue. pipe (writeStream); console. log ('program execution is complete. ');
Case: compressed file express. js
[Code] var fs = require ('fs'); var zlib = require ('zlib '); // compress input.txt to input.gzfs.createReadStream('input.txt '). pipe (zlib. createGzip () .pipe(fs.createWriteStream('input.gz '); console. log ('compressed file ');
Case: decompress the file decompress. js
[Code] var fs = require ('fs'); var zlib = require ('zlib '); // decompress input.gz to input.gz.txtfs.createReadStream('input.gz '). pipe (zlib. createGunzip () .pipe(fs.createWriteStream('input.gz.txt '); console. log ('decompress The file ');
The above is the content of Node. js Stream (Stream). For more information, please follow the PHP Chinese Network (www.php1.cn )!