- All Stream objects are also instances of EventEmitter, and the events commonly used by Stream objects are
event name Triggering conditions data Triggered when there is data to read end Triggered when there is no data to read error Triggered when an error occurs during reading or writing finish Fired when all data has been written to the underlying system - Read data from stream read
data readData.js code is as followsvar fs = require('fs'); var readerStream = fs.createReadStream('input.txt'); readerStream.setEncoding('UTF-8'); var data = ''; readerStream.on('data',function(chunk){ data += chunk; }); readerStream.on('end',function(){ console.log(data); }); readerStream.on('error',function(err){ console.log('Custom error log:',err.stack); }); console.log('Program completed');
operation result>node readData.js program is completed Here is the tested file; hello,this is a test file.
- Write data to the stream write
data writeData.js code is as followsvar fs = require('fs'); var writerStream = fs.createWriteStream('output.txt'); writerStream.write('Really, I didn't go out in such a good weather sss','utf-8'); writerStream.end(); writerStream.on('finish',function(){ console.log('写入完成'); }); writerStream.on('error',function(err){ console.log('自定义错误日志:',err.stack); }); console.log('程序执行完毕');
运行结果如下>node Stream.js 程序执行完毕 写入完成
- 管道与链式流
pipeStream.js代码如下var fs = require('fs'); var zlib = require('zlib'); var readerStream = fs.createReadStream('input.txt'); var writeCompressGz = fs.createWriteStream('compress.txt.gz'); writeCompressGz.on('finish',function(){ fs.createReadStream('compress.txt.gz') .pipe(zlib.createGunzip()) .pipe(fs.createWriteStream('compress.txt')); }); readerStream.pipe(zlib.createGzip()).pipe(writeCompressGz); console.log('程序执行完毕');
05. Stream Stream
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=326267013&siteId=291194637
Recommended
Ranking