1valdis
1valdis

Reputation: 1104

How to rename file without overwriting existing?

Lets say I have two files:

/1.txt

/2.txt

Now if I call fs.rename('/1.txt', '/2.txt'), it will replace 2.txt with 1.txt.

They say this is how rename works it Linux and all. But I don't want to replace if a file on a new path exists already. Ideally I want to throw some error on that, like EEXIST. Using fs.existsSync, fs.stat or other checks before renaming introduces race condition as I understand.

Upvotes: 3

Views: 1678

Answers (1)

m1ch4ls
m1ch4ls

Reputation: 3425

To avoid race condition you will need some kind of locking mechanism.

On Linux system it's pretty standard to use a lockfile - generally it's an empty file or directory that serves as a check that some sequence of operations is taking place. Similar to database row/table locking creating and removing of lockfile is atomic - the rest of the operations are not.

I would use proper-lockfile package and move from fs-extra for this:

const lockfile = require('proper-lockfile');
const fs = require('fs-extra');

lockfile.lock('some/file')
  .then(() => fs.move('/tmp/file', 'some/file'))
  .finally(() => lockfile.unlock('some/file'));

Also note that any logic working with some/file has to respect the lockfile otherwise the race condition would still exists.

Upvotes: 1

Related Questions