Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolve filesystem paths (possibly with symlinks) with Node.js

Tags:

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. 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?

like image 658
Brad Avatar asked Oct 15 '14 00:10

Brad


1 Answers

Node also has fs.realpath() so that should work the same way as in PHP.

like image 84
mscdex Avatar answered Sep 28 '22 04:09

mscdex