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
. If the file is /var/www/../../etc/passwd
, I need to return false
.
In PHP land, I usually use a function called realpath()
:
realpath() expands all symbolic links and resolves references to '/./', '/../' and extra '/' characters in the input path and returns the canonicalized absolute pathname.
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. If it is, I return true
.
Is there a function for Node.js that achieves the same goal? path.resolve()
gets me half way, but doesn't handle any symlinks that are actually in the filesystem. fs.readlink()
has absolutely no documentation at all, and may not directly apply since I won't always have symlinks.
Must I loop through each part of the path, resolving symlinks as I go, or is there a more canonical method?
Node also has fs.realpath()
so that should work the same way as in PHP.
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