问题
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.
回答1:
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.
回答2:
I've just faced the same issue: sometimes fs.readlink
returns a relative path, sometimes it returns an absolute path.
(proper error handling not implemented to keep things simple)
const fs = require('fs');
const pathPckg = require('path');
async function getTarLinkOfSymLink(path){
return new Promise((resolve, reject)=>{
fs.readlink(path, (err, tarPath)=>{
if(err){
console.log(err.message);
return resolve('');
}
const baseSrcPath = pathPckg.dirname(path);
return resolve( pathPckg.resolve(baseSrcPath, tarPath) );
});
});
}
// usage:
const path = '/example/symbolic/link/path';
const tarPath = await getTarLinkOfSymLink(path);
The code works if the symbolic link is either a file or a directory/folder - tested on Linux
来源:https://stackoverflow.com/questions/51896873/how-to-read-a-symlink-in-node-js