Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a symlink in Node.js

I want to read a symlink, and get the details of the link itself, not the contents of the linked file. How do I do that in Node, in a cross-platform way?

I can detect symlinks easily using lstat, no problem. Once I know the path of the file, and that it is a symlink though, how can I read it? fs.readFile always reads the target file, or throws an error for reading a directory for links to directories.

There is a fs.constants.O_SYMLINK constant, which in theory solves this on OSX, but it seems to be undefined on both Ubuntu & Windows 10.

like image 882
Tim Perry Avatar asked Aug 17 '18 13:08

Tim Perry


People also ask

How can I see symlink points?

Simplest way: cd to where the symbolic link is located and do ls -l to list the details of the files. The part to the right of -> after the symbolic link is the destination to which it is pointing.

What is a symlink node JS?

A symbolic link(or symlink) is used to describe any file that contains a reference to some other file or directory which can be in the form of a relative or absolute path. In a way, you can say a symlink is a shortcut file.

Can a symlink point to a directory?

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.


1 Answers

If you have determined that the file is a symlink try this:

fs.readlink("./mysimlink", function (err, linkString) { 
         // .. do some error handling here .. 
         console.log(linkString) 
});

Confirmed as working on Linux.

You could then use fs.realpath() to turn it into a full path. Be aware though that linkString can be just a filename or relative path as well as a fully qualified path so you may have to get fs.realpath() for the symlink, determine its directory part and prefix it to linkString before using fs.realpath() on it.

like image 121
Voltaire Avatar answered Sep 27 '22 17:09

Voltaire