25

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?

Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
  • 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"_). – robertklep Apr 23 '15 at 11:41
  • 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: http://serverfault.com/questions/389997/how-to-override-update-a-symlink – vanadium23 Apr 23 '15 at 13:01
  • @robertklep 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. – Ionică Bizău Apr 23 '15 at 15:47
  • @vanadium23 I know I can use `ln -f` but, I don't want to. I want to use the file system api. – Ionică Bizău Apr 23 '15 at 15:48
  • @IonicăBizău if by "native" you mean "using `fs`", then the answer is no :-) – robertklep Apr 23 '15 at 16:16
  • 1
    @robertklep OK, so I built a module to do this thing. :) – Ionică Bizău Apr 23 '15 at 18:15

2 Answers2

38

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

Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
  • 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: https://github.com/IonicaBizau/node-lnf/issues/14 – kanaka Jul 05 '23 at 14:50
11

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).