节点:如何等待文件完成后再处理? [英] Node: How to wait until a file is completed before processing it?

查看:104
本文介绍了节点:如何等待文件完成后再处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是,我不确定何时已成功写入文件且文件已关闭.考虑以下情况:

My Problem is that I can not be sure when a file has been successfully written to and the file has been closed. Consider the following case:

var fs = require('fs');
var outs = fs.createWriteStream('/tmp/file.txt');
var ins = <some input stream>

...
ins.on('data', function(chunk) { out.write(chunk); });
...
ins.on('end', function() {
   outs.end();
   outs.destroySoon();
   fs.stat('/tmp/file.txt', function(err, info) {

      // PROBLEM: Here info.size will not match the actual number of bytes.
      // However if I wait for a few seconds and then call fs.stat the file has been flushed.
   });
});

那么,如何在访问文件之前强制或以其他方式确保已正确刷新文件?我需要确保文件在那里并且完整,因为我的代码必须产生一个外部进程来读取和处理文件.

So, how do I force or otherwise ensure that the file has been properly flushed before accessing it? I need to be sure that the file is there and complete, as my code has to spawn an external process to read and process the file.

推荐答案

writeable stream's close 事件:

outs.on('close', function() {
  <<spawn your process>>
});

此外,end之后不需要destroySoon,它们是一模一样.

Also, no need for the destroySoon after the end, they are one and the same.

这篇关于节点:如何等待文件完成后再处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆