How to force the creation of a symbolic link to override the existing symbolic link?

I use the fs module to create symbolic links.

 fs.symlink("target", "path/to/symlink", function (e) { if (e) { ... } }); 

If path/to/symlink already exists, an error is sent in the callback.

How can I force a symlink and override an existing symlink?

Is there any other option than check error + delete existing symlink + try again ?

+6
source share
2 answers

When using the ln command line tool, we can do this using the -f (force) flag

 ln -sf target symlink-name 

However, this is not possible with the fs API if we do not implement this function in the module.

I created lnf , a module for overriding existing symbolic links.

 // Dependencies var Lnf = require("lnf"); // Create the symlink Lnf.sync("foo", __dirname + "/baz"); // Override it Lnf("bar", __dirname + "/baz", function (err) { console.log(err || "Overriden the baz symlink."); }); 

Read the full documentation in the GitHub repository

+5
source

You can create a temporary symbolic link with a different (unique) name and then rename it.

Use fs.symlinkSync(path, tempName) and then fs.rename(tempName, name) .

This may be better than deleting a file when another application depends on its existence (and may accidentally access it when it is deleted, but not yet recreated).

+2
source

Source: https://habr.com/ru/post/985766/


All Articles