简体   繁体   English

使用Node.js解析文件系统路径(可能带有符号链接)

[英]Resolve filesystem paths (possibly with symlinks) with Node.js

I need a way to verify whether or not a file is under a specific path. 我需要一种方法来验证文件是否在特定路径下。 If the path is /var/www and the file is /var/www/something/something-else/file , I need to return true . 如果路径是/var/www并且文件是/var/www/something/something-else/file ,我需要返回true If the file is /var/www/../../etc/passwd , I need to return false . 如果文件是/var/www/../../etc/passwd ,我需要返回false

In PHP land, I usually use a function called realpath() : 在PHP领域,我通常使用一个名为realpath()的函数:

realpath() expands all symbolic links and resolves references to '/./', '/../' and extra '/' characters in the input path and returns the canonicalized absolute pathname. realpath()扩展所有符号链接并解析对输入路径中的'/./','/../'和额外'/'字符的引用,并返回规范化的绝对​​路径名。

I run realpath() on both the desired path and the full file path, then determine if the desired path is a substring of the result of the fully resolved file path. 我在所需的路径和完整的文件路径上运行realpath() ,然后确定所需的路径是否是完全解析的文件路径的结果的子字符串。 If it is, I return true . 如果是的话,我会回归true

Is there a function for Node.js that achieves the same goal? Node.js是否有一个实现相同目标的功能? path.resolve() gets me half way, but doesn't handle any symlinks that are actually in the filesystem. path.resolve()让我走了一半,但没有处理文件系统中实际存在的任何符号链接。 fs.readlink() has absolutely no documentation at all, and may not directly apply since I won't always have symlinks. fs.readlink()完全没有文档,可能不会直接应用,因为我不会总是有符号链接。

Must I loop through each part of the path, resolving symlinks as I go, or is there a more canonical method? 我必须循环遍历路径的每个部分,在我去的时候解析符号链接,还是有更规范的方法?

Node也有fs.realpath()所以它的工作方式与PHP相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM