title: How do I find out whether a file is within a directory with Node.js?
body: <p>Given two absolute or relative paths, <code>A</code> and <code>B</code>, I want to find out whether <code>B</code> is "inside of" the directory <code>A</code>—not just in the directory itself, but potentially in a subdirectory. I'd like to do this without a potentially huge number of <code>fs.readdir</code> calls.</p>
  
  <p>For instance, if <code>A</code> is <code>/</code> and <code>B</code> is <code>/foo/bar/baz</code>, it should be pretty obvious that <code>B</code> is within <code>A</code>; the recursive <code>readdir</code> approach would be extremely inefficient.</p>
  
  <p>One obvious idea is to convert both paths to absolute form, then check if the string form of <code>B</code>'s absolute path starts with the string form of <code>A</code>'s. However, there are two problems:</p>
  
  <ol>
  <li>How do you convert the relative paths to absolute paths?</li>
  <li>What about symbolic links and such?</li>
  </ol>
  
  <p>I'll accept answers that make calls to Linux utilities (other than <code>rm -rf</code>... which <em>technically</em> could be used to solve the problem) or third-party Node libraries.</p>