流是一种等对文件读写、网络通信等过程中有大量数据处理和管理的高效处理方式。与其他数据处理方式相比,有2大优势:
1)内存消耗低,无需全部加载进内存,才可以处理;
2)时间快,获得部分数据就开始处理;
流的类型有4种:
1)可写流(writable):只能读取数据
2)可读流(readable):只可写入数据
3)双工流(duplex):既能读也可以写
4)转换流(transform):既能读也可以写。类似于双工流、但其输出是其输入的转换。
Node.js内置了stream模块,专门负责处理所有流操作。
/**
* 流:大量数据管理的高效处理方式
*/
const fs = require("fs");
//可写流
var writeStream = fs.createWriteStream("song.txt");
var writeStr = "天籁之音";
writeStream.write(writeStr,"UTF8");
writeStream.end();
writeStream.on("finish",function(){
console.log("文件写入完成!");
});
writeStream.on("error",function(err){
console.log("文件写入错误:",err);
});
//可读流
var readStream = fs.createReadStream("song.txt");
var resStr = "";
readStream.on("data",function(chunk){
resStr += chunk;
});
readStream.on("end",function(chunk){
console.log("song1.txt文件内容读取完成:",resStr);
});
readStream.on("error",function(err){
console.log("文件读取错误:",err);
});
//可读可写双流
var readStream2 = fs.createReadStream("song.txt");
var writeStream2 = fs.createWriteStream("song2.txt");
readStream2.pipe(writeStream2);
readStream2.on("end",()=>{
writeStream2.end();
var readStream3 = fs.createReadStream("song2.txt");
var str = "";
readStream3.on("data",function(chunk){
str += chunk;
});
readStream3.on("end",function(chunk){
console.log("song2.txt文件内容读取完成:",str);
});
readStream3.on("error",function(err){
console.log("文件读取错误:",err);
});
});
readStream2.on("error",function(err){
readStream2.unpipe();
});
运行结果如下: