How to read a symlink in Node.js

眉间皱痕 提交于 2020-01-24 05:44:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!