如何在Node.js中读取符号链接 [英] How to read a symlink in Node.js

查看:264
本文介绍了如何在Node.js中读取符号链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想阅读符号链接,并获取链接本身的详细信息,而不是链接文件的内容.如何在Node中以跨平台方式做到这一点?

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?

我可以使用lstat轻松检测符号链接,没问题.一旦我知道了文件的路径,尽管它是一个符号链接,如何读取它? fs.readFile总是读取目标文件,或者在读取目录以获取目录链接时抛出错误.

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.

有一个fs.constants.O_SYMLINK常量,理论上可以在OSX上解决这个问题,但是在Ubuntu& amp;上似乎都没有定义. Windows 10.

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.

推荐答案

如果您确定该文件是符号链接,请尝试以下操作:

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) 
});

确认可以在Linux上运行.

Confirmed as working on Linux.

然后可以使用fs.realpath()将其转换为完整路径.请注意,尽管linkString可以是文件名或相对路径,也可以是完全限定的路径,所以在使用fs.realpath()作为符号链接,确定其目录部分并将其前缀为linkString >.

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.

这篇关于如何在Node.js中读取符号链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆