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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With