- 所有Stream对象同时也是EventEmitter的实例,Stream对象常用的事件有
事件名 触发条件 data 当有数据可读时触发 end 没有数据可读时触发 error 在读取或写入过程中发生错误时触发 finish 所有数据已被写入到底层系统时触发 - 从流读取数据
读取数据readData.js代码如下var 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('自定义错误日志:',err.stack); }); console.log('程序执行完毕');
运行结果>node readData.js 程序执行完毕 这里是被测试的文件; hello,this is a test file.
- 向流写数据
写数据writeData.js代码如下var fs = require('fs'); var writerStream = fs.createWriteStream('output.txt'); writerStream.write('真是的,这么好的天气没出门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
最新推荐文章于 2024-04-26 17:15:36 发布