//文件流
//读取流
//写入流
let fs=require('fs');
//读取流
let data="";//接收读取的数据
//创建读取流
let readStream=fs.createReadStream('public/jq.txt',{flags:'r+',encoding:'utf-8',start:0,end:1024});
//设置读取流的编码格式
//readStream.setEncoding('utf-8');
//使用流的监听事件 去监听
readStream.on('data',(res)=>{
//当有数据可读的时候触发
data+=res;
});
readStream.on('end',()=>{
//当没有数据可读的时候
//console.log(data);
//创建写入
let writeStream=fs.createWriteStream('public/data.txt',{flags:'r+',encoding:'utf-8'});
writeStream.write(data);
});
readStream.on('error',(err)=>{
//读取或者写入的时候触发事件
console.log(err);
});
//写入流
//创建写入流
let writeStream=fs.createWriteStream('public/data.txt');
//设置写入的数据和编码
writeStream.write('写入流','utf-8');
//写入完成
writeStream.end();
writeStream.on('finish',()=>{
console.log("写入完成");
});
//管道流 边读边写
let readStream=fs.createReadStream('public/jq.txt');
let writeStream=fs.createWriteStream('public/data.txt');
readStream.pipe(writeStream);
//链式流 应用于管道流
let zib=require('zlib');//文件压缩
fs.createReadStream('public/data.txt').pipe(zib.createGzip()).pipe(fs.createWriteStream('public/data.zip'));
//应用
let zib=require('zlib');
fs.createReadStream('public/vue.docx').pipe(zib.createGzip()).pipe(fs.createWriteStream('public/vue.docx.zip'));
Node js 流的使用
最新推荐文章于 2024-10-14 13:12:16 发布