gpt4 book ai didi

Windows 上的 Node.js 0.12.7 writeFileSync 和子进程

转载 作者:太空宇宙 更新时间:2023-11-03 22:34:22 25 4
gpt4 key购买 nike

我的nodejs代码将http请求写入JSON文件,然后调用子进程根据写入的JSON文件中的参数运行。

app.post("/run_with_parameters", function(req, res){
fs.writeFileSync("parameters.json", JSON.stringify(req.body));
child_process.stdin.write("parameters.json"); //child process will read json and act accordingly
});

在 Windows 机器上,“子进程”有时会获取旧参数而不是新参数,我怀疑这是因为 fs.writeFileSync 在返回运行之前没有完成写入磁盘下一个声明。 (根据this post)。

这是 Node.js 的错误/功能吗?或者它只存在于 Windows 机器上?

如果我这样编码会更好吗?

app.post("/run_with_parameters", function(req, res){
fs.writeFile("parameters.json", JSON.stringify(req.body), function(){
child_process.stdin.write("parameters.json"); //child process will read json and act accordingly

});
});

这是否能保证“子进程”始终获得更新的“parameters.json”?

最佳答案

您链接到的文章(具体讨论 ZFS 时)表明,这些文件操作都不能保证回调完成时数据已写入。然而finish流的事件说:

When the end() method has been called, and all data has been flushed to the underlying system, this event is emitted.

所以你可以使用createWriteStream ,写入它并在 finish 事件上通过管道传输到您的子进程。如果我正确解释文档,您的文件将在那里并包含内容。

关于Windows 上的 Node.js 0.12.7 writeFileSync 和子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31714042/

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