8

Note: using Node.js 8

I have a series of symlinks: a -> b -> c

I need to resolve the initial symlink a to its target destination b. How can this be accomplished in Node.js?

The fs.realpath function resolves chains of symlinks, so it resolves a to c. This is not the desired behavior.

I've also attempted to find an npm package to do this, but haven't had any luck so far.

I thought maybe I could fs.open the symlink and read the contents, but I could not figure out how to access the documented fs.constants.O_SYMLINK constant, probably because I'm on Node 8.

rich remer
  • 3,407
  • 2
  • 34
  • 47

1 Answers1

14

I searched Node.js documentation for the word "symlink", but the Node documentation just refers to these as a "link". The solution is to use fs.readlink():

const {readlink} = require("fs");

fs.readlink("a", (err, target) => {
    if (!err) console.log(target);    // prints "b"
});
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
rich remer
  • 3,407
  • 2
  • 34
  • 47