1.以流的方式读取文件
//分次数来读取文件
const fs = require('fs');
const readStream = fs.createReadStream('input.txt');
let str = '';
let count =0;
readStream.on('data',(chunk)=>{
str+=chunk;
count++;
})
//读取完成
readStream.on('end',(chunk)=>{
console.log(str);
console.log(count);
})
readStream.on('error',(err)=>{
console.log(err)
})
2.以流的方式写入文件
const fs = require('fs');
const writeStream = fs.createWriteStream('output.txt');
let data ='这是即将写入的内容\n';
for(var i=0;i<100;i++){
writeStream.write(data,'utf8');
}
writeStream.end()
writeStream.on('finish',()=>{
console.log('end()之后会触发finish事件,写入完成')
})
writeStream.on('error',(err)=>{
console.log(err)
})
3.管道流
//管道提供了一个输出流到输入流的机制,通常用于从一个流中获取数据 并将数据传递到另外一个流中
const fs =require('fs');
const readStream = fs.createReadStream('input.txt');
const writeStream = fs.createWriteStream('output.txt');
readStream.pipe(writeStream);
console.log('程序执行完毕');
网友评论