How to find out if a file is in a directory with Node.js?

Given the two absolute or relative paths, A and B , I want to find out if B “inside” the directory A not only in the directory itself, but also potentially in a subdirectory. I would like to do this without a potentially huge number of fs.readdir calls.

For example, if A - / and B - /foo/bar/baz , it should be pretty obvious that B is inside A ; readdir recursive approach would be extremely inefficient.

One obvious idea is to convert both paths to absolute form, and then check if the string form of the absolute path B begins with the string form A However, there are two problems:

  • How do you convert relative paths to absolute paths?
  • How about symbolic links, etc.

I will accept answers that cause calls to Linux utilities (except rm -rf ... which technically can be used to solve the problem) or third-party Node libraries.

+4
source share
1 answer
 var fs = require('fs'); var a = fs.realpathSync('/home/mak/www'); // /var/www var b = fs.realpathSync('/var/www/test/index.html'); var b_in_a = b.indexOf(a) == 0; var a_is_dir = fs.statSync(a).isDirectory(); 

fs.*Sync also has asynchronous versions, see fs module .

fs.realpathSync and fs.statSync will fs.statSync if the path does not exist.

+8
source

All Articles