How to force a symlink creation by overriding the existing symlink?
Asked Answered
E

2

26

I use the fs module to create symlinks.

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

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

How can I force symlink creation and override the existing symlink?

Is there another alternative than check error + delete existing symlink + try again?

Emission answered 23/4, 2015 at 9:56 Comment(6)
There may be modules that will provide such functionality, but in the end it will also use the method you describe (that, or "check existence + delete if exists + symlink").Easily
I don't how to do this in js, but in linux you can override symlink, so you can call a shell script from node. Source: serverfault.com/questions/389997/…Morra
@Easily Well, for sure. I can create a module as well, just for this thing, but I'd be interested if there is a native way.Genocide
@Morra I know I can use ln -f but, I don't want to. I want to use the file system api.Genocide
@IonicăBizău if by "native" you mean "using fs", then the answer is no :-)Easily
@Easily OK, so I built a module to do this thing. :)Genocide
E
39

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 using the fs API unless we implement this feature in a module.

I created lnf - a module to override existing symlinks.

// 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 on the GitHub repository

Emission answered 23/4, 2015 at 18:13 Comment(1)
WARNING: the method currently used in the lnf module does an unlink followed by a symlink. That isn't concurrency safe and leaves a race condition where some other process may create a file between the unlink and the symlink (among other issues). There is a ticket noting this: github.com/IonicaBizau/node-lnf/issues/14Garfieldgarfinkel
K
13

You can create temporary symlink with different (unique) name and then rename it.

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

It may be better than deleting the file when other application depends on its existence (and may accidentaly access it when it is deleted, but not yet recreated).

Kaden answered 23/12, 2015 at 11:43 Comment(1)
As I didn't know that's how POSIX rename() was specified.+1Radiochemical

© 2022 - 2024 — McMap. All rights reserved.