//57、可写流基本用法
writestream.js
const fs = require('fs');
const path = require('path');
//内部也是基于Events模块,如果文件不存在会创建文件,默认会清空文件并写入
//fs.open fs.write
let ws = fs.createWriteStream(path.resolve(__dirname,'name.txt'),{
flags:'w',
encoding:'utf8',
mode:0o666,
autoClose:true,
start:0,
highWaterMark:3 //(预期占用的内存)16K(指代的不是每次写多少)不会影响内容的写入
//达到或者超过预期后返回的值就是false
});
//ws.write写入的内容
//ws.end可以关闭文件
//ws.on('drain',()=>{});
//ws.open()
//ws.close()
//写入的内容必须是string或者buffer ws.write(1); 报错TypeError [ERR_INVALID_ARG_TYPE]: The
//"chunk" argument must be of type string or an instance of Buffer or
//Uint8Array. Received type number (1)
let flag = ws.write('hello',()=>{
console.log('成功1');
});
console.log(flag);
flag = ws.write('world',()=>{
console.log('成功2');
});
console.log(flag);
flag = ws.write('!!!',()=>{
console.log('成功3');
})
/*
C:\Users\dptech\Desktop\test>node writestream.js
false
false
false
成功1
成功2
成功3
*/
/*
ws.end('!!!',()=>{
console.log('成功3');
});*/
ws.on('drain',()=>{
console.log('drain');
})
/*
C:\Users\dptech\Desktop\test>node writestream.js
false
false
成功1
drain
成功2
成功3
*/
//内部会维护一个变量,这个变量会统计写入的个数,当达到highWaterMark时,会返回false,内容写入后,会在统计的数量的基础上减少
//drain触发的条件是1、必须达到预期或者过预期 2、内存中的内容全部清空后会触发drain事件
writestream.js
//我希望写入10个字节,只占用一个字节的内存
const fs = require('fs');
const path = require('path');
let ws = fs.createWriteStream(path.resolve(__dirname,'name.txt'),{
highWaterMark:3 //是预期 可以根据这个值来控制写入的速率
});
let index = 0;
function write(){
let flag = true;//标识是否可以写入
while(flag && index < 10){
flag = ws.write(index + '');
index++;
}
if(index == 10)
{
ws.end('!!');//文件的关闭操作, ws.write+ws.close
}
}
write();
ws.on('drain',()=>{
console.log('----------');
write();
})
ws.on('close',()=>{
console.log('close');
});
//w fs.open('a.txt', 'w') w操作符
//name.txt 0123456789!!
/*
C:\Users\dptech\Desktop\test>node writestream1.js
----------
----------
----------
close
*/