Learning points:
Read data from the stream
Write to the stream
Pipe stream
Chain stream
Node.js Stream(Stream)
Read data from the stream
Case: main.js
[code]var fs = require('fs'); var data = ''; // 创建可读流 var readerStream = fs.createReadStream('input.txt'); // 设置utf8编码 readerStream.setEncoding('UTF8'); // 处理流事件 // data 当有数据可读时触发 readerStream.on('data', function (chunk) { data += chunk; }); // end 当没有数据读时触发 readerStream.on('end', function () { console.log(data); }); // error 在接收和写入过程中发生错误时触发。 readerStream.on('error', function (err) { console.log(err.stack); }); console.log('程序执行完毕。');
Case: main2.js
[code]var fs = require('fs'); var data = '我是谁?'; // 创建写入流 var writeStream = fs.createWriteStream('ouput.txt'); // 编码 writeStream.write(data, 'UTF8'); // 标记文件末尾 writeStream.end(); // 处理流事件 // finish 所有数据已被写入到底层系统时触发。 writeStream.on('finish', function () { console.log('写入完成'); }); // error 在读入和写入数据是触发 writeStream.on('error', function (err) { console.log(err.stack); }); console.log('程序执行完毕。');
Input data from one stream into another stream
Case: pipe.js
[code]var fs = require('fs'); // 创建可读流 var readerStream = fs.createReadStream('input.txt'); // 创建写入流 var writeStream = fs.createWriteStream('ouput.txt'); // 管道读写 readerStream.pipe(writeStream); console.log('程序执行完毕。');
is to connect multiple input and output streams
Case: compression File express.js
[code]var fs = require('fs'); var zlib = require('zlib'); // 将 input.txt 压缩为 input.gz fs.createReadStream('input.txt') .pipe(zlib.createGzip()) .pipe(fs.createWriteStream('input.gz')); console.log('文件压缩完毕');
[code]var fs = require('fs'); var zlib = require('zlib'); // 解压 input.gz 为 input.gz.txt fs.createReadStream('input.gz') .pipe(zlib.createGunzip()) .pipe(fs.createWriteStream('input.gz.txt')); console.log('解压文件完毕');