Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js determine path targeted by symlink

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.

like image 472
rich remer Avatar asked Sep 06 '18 23:09

rich remer


People also ask

What is a symlink path?

A symbolic link, also known as a soft link or symlink, is a special file pointing to another file or directory using an absolute or relative path. Symbolic links are similar to shortcuts in Windows and are useful when you need quick access to files or folders with long paths.

How do I find a named symbolic link?

The first way is by using the ls command in UNIX which displays files, directories, and links in any directory and the other way is by using UNIX find command which has the ability to search any kind of file e.g. file, directory, or link.

Does NPM use symlinks?

First, npm link in a package folder with no arguments will create a symlink in the global folder {prefix}/lib/node_modules/<package> that links to the package where the npm link command was executed. It will also link any bins in the package to {prefix}/bin/{name} .


1 Answers

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"
});
like image 154
rich remer Avatar answered Oct 21 '22 09:10

rich remer