Given two absolute or relative paths, A and B, I want to find out whether B is “inside of” the directory A—not just in the directory itself, but potentially in a subdirectory. I’d like to do this without a potentially huge number of fs.readdir calls.
For instance, if A is / and B is /foo/bar/baz, it should be pretty obvious that B is within A; the recursive readdir approach would be extremely inefficient.
One obvious idea is to convert both paths to absolute form, then check if the string form of B‘s absolute path starts with the string form of A‘s. However, there are two problems:
- How do you convert the relative paths to absolute paths?
- What about symbolic links and such?
I’ll accept answers that make calls to Linux utilities (other than rm -rf… which technically could be used to solve the problem) or third-party Node libraries.
fs.*Syncalso have asynchronous versions, see fs module.fs.realpathSyncandfs.statSyncwill throw if the path does not exist.