gpt4 book ai didi

file - Node : How to wait until a file is completed before processing it?

转载 作者:搜寻专家 更新时间:2023-10-31 22:19:52 25 4
gpt4 key购买 nike

我的问题是我无法确定文件何时成功写入以及文件何时关闭。考虑以下情况:

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.
});
});

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

最佳答案

可写流中对文件进行后处理 close事件:

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

此外,end 之后不需要destroySoon,它们是one and the same .

关于file - Node : How to wait until a file is completed before processing it?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14639388/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com