Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename file without overwriting existing?

Tags:

node.js

fs

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.

like image 504
1valdis Avatar asked Nov 26 '25 11:11

1valdis


1 Answers

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.

like image 135
m1ch4ls Avatar answered Nov 29 '25 01:11

m1ch4ls



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!