Reputation: 334
const path = require('path');
const fs = require('fs');
const os = require('os');
const from_dir = path.resolve(os.homedir(), './from_dir');
const to_dir= path.resolve(os.homedir(), './new_dir');
fs.renameSync(from_dir, to_dir);
Suppose I have the following snippet of code in a NodeJS application, and my goal is to rename "from_dir" to "to_dir". Based on my understanding, the rename operation is supposed to be atomic. Can I also rely on this operation to never corrupt the "from_dir" directory contents during the rename process, even if the process is being forcefully shut down during? Or is it better to first copy the contents of the directory to a backup, and then attempt to rename (something equivalent to cp -r ~/from_dir ~/from_dir_backup
)? I have tried to reproduce such a scenario and couldn't do it.
Upvotes: 0
Views: 662
Reputation: 2438
Under the hood, the rename
and renameSync
functions from fs
invoke their low-level counterpart: the rename
syscall. That syscall only updates the name which points to the directory's inode, but does not alter the contents of the directory that you're moving.
You can verify this yourself: check the inode number of the directory at the start (using the stat
command), do an fs.renameSync
, and afterwards inspect the inode number of the destination. They're the same, which means the directory was not re-created from scratch, but indeed renamed with its contents intact.
Now, POSIX does not require that the operation be atomic per se - in fact, the Linux manpage (man 2 rename
) has this to say on the topic on atomicity:
If newpath already exists, it will be atomically replaced, so that there is no point at which another process attempting to access newpath will find it missing. However, there will probably be a window in which both oldpath and newpath refer to the file being renamed.
I am not exactly sure if this corner case (2 links) is possible with directories, since I've never been able to create more than 1 hard link to a directory, but the manpage seems quite reassuring in that the directory is not going to disappear or get unlinked into oblivion.
Upvotes: 1