同步、异步、简单文件的写入都不适合大文件的写入,性能较差,容易导致内存溢出。

创建、写入、关闭可写流

  1. // 创建可写流
  2. var wf = fs.createWriteStream(file)
  3. // 写入
  4. wf.write(data);
  5. // 关闭
  6. wf.end();

监听流

可以通过监听流的open和close事件来监听流的打开和关闭。有两种方式:ononce

  • once绑定的是一个一次性事件,事件将会在触发一次后自动失效
  1. wf.on(eventStr, callback);
  2. wf.once(eventStr, callback);

例子

  1. var fs = require('fs');
  2. // 创建写入流
  3. var wf = fs.createWriteStream('test4.txt');
  4. // 绑定监听
  5. wf.on('open', function () {
  6. console.log('文件已打开...')
  7. });
  8. wf.once('close', function () {
  9. console.log('文件已关闭...');
  10. });
  11. // 写入
  12. wf.write("hello world");
  13. wf.write("你好,世界");
  14. wf.write("中华人民共和国");
  15. // 关闭流
  16. wf.end();