有这么一个需求:想把input里面的内容写到outInput里面去,但是上面的方法都是把文档里面的内容重置了,只想添加,而且保留原内容怎么办呢?

可以在可读流创建完毕的回调函数里面进行操作,看代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
let fs = require('fs');
let data = '';
let data2 = '你的小青蛙是真的可爱';

//1.读取流
let readStream = fs.createReadStream("input.txt"); //创建可读流
readStream.setEncoding('UTF8'); //设置utf-8编码

//处理流事件
readStream.on('data', chunk => data += chunk);
readStream.on('end', () => writeS(data));
readStream.on("error", err => console.log(err.strck));
console.log("程序1执行完毕");

//2.写入流
let writeS = dataS =>{ //创建可写流
let writeStream = fs.createWriteStream("outInput.txt");
writeStream.write(data2+dataS, "UTF8"); //使用utf-8写入流
writeStream.end(); //标记文件末尾

//处理事件流
writeStream.on("finish", () => console.log("写入完成"));
writeStream.on("error", err => console.log(err.stack));
console.log("程序2执行完毕");
}

如此,便可以啦!


如上面可能存在覆盖状态,可以设置写入流的追加参数来解决:

1
2
3
4
var fs = require('fs');
var read = fs.createReadStream('input.txt');
var write = fs.createWriteStream('out.txt', { 'flags': 'a' }); //设置第二个参数append
read.pipe(write); //管道流读写操作