有这么一个需求:想把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 = '你的小青蛙是真的可爱';
let readStream = fs.createReadStream("input.txt"); readStream.setEncoding('UTF8');
readStream.on('data', chunk => data += chunk); readStream.on('end', () => writeS(data)); readStream.on("error", err => console.log(err.strck)); console.log("程序1执行完毕");
let writeS = dataS =>{ let writeStream = fs.createWriteStream("outInput.txt"); writeStream.write(data2+dataS, "UTF8"); 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' }); read.pipe(write);
|