在Node.js中以事务方式写入文件 [英] Transactionally writing files in Node.js

查看:133
本文介绍了在Node.js中以事务方式写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Node.js应用程序,该应用程序将一些配置数据存储在文件中。如果更改某些设置,则配置文件将写入磁盘。

I have a Node.js application that stores some configuration data in a file. If you change some settings, the configuration file is written to disk.

目前,我正在使用简单的 fs.writeFile

At the moment, I am using a simple fs.writeFile.

现在我的问题是:在写入文件时Node.js崩溃时会发生什么?有机会在磁盘上有损坏的文件吗?还是Node.js保证以原子方式写入文件,以便旧版本或新版本均有效?

Now my question is: What happens when Node.js crashes while the file is being written? Is there the chance to have a corrupt file on disk? Or does Node.js guarantee that the file is written in an atomic way, so that either the old or the new version is valid?

如果无效,我该如何实现这样的保证?

If not, how could I implement such a guarantee? Are there any modules for this?

推荐答案


当文件中的Node.js崩溃时会发生什么?被写?
是否有机会在磁盘上存在损坏的文件?还是Node.js
保证以原子方式写入文件,以便旧版本或新版本的
都有效?

What happens when Node.js crashes while the file is being written? Is there the chance to have a corrupt file on disk? Or does Node.js guarantee that the file is written in an atomic way, so that either the old or the new version is valid?

节点仅在系统调用上实现一个(瘦)异步包装程序,因此它不提供有关写入原子性的任何保证。实际上, fs.writeAll 反复调用 fs.write ,直到写入所有数据。没错,当Node.js崩溃时,您可能最终会损坏文件。

Node implements only a (thin) async wrapper over system calls, thus it does not provide any guarantees about atomicity of writes. In fact, fs.writeAll repeatedly calls fs.write until all data is written. You are right that when Node.js crashes, you may end up with a corrupted file.


如果没有,我该如何实现保证?

If not, how could I implement such a guarantee? Are there any modules for this?

我能想到的最简单的解决方案是例如对于FTP上传:

The simplest solution I can come up with is the one used e.g. for FTP uploads:


  1. 将内容保存到其他名称的临时文件中。

  2. 何时将内容写入磁盘,将临时文件重命名为目标文件。

手册页表示,重命名保证书以保留新路径的实例(在Unix系统上,例如Linux或OSX)。

The man page says that rename guarantees to leave an instance of newpath in place (on Unix systems like Linux or OSX).

这篇关于在Node.js中以事务方式写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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