title: Safe path.resolve without escaping from parent
body: <p>I am writing an (expressjs) http service, which gets a relative path as user input on every call, reads a file from the filesystem based on that path, and processes it, like:</p>
  
  <pre><code>app.get("/api", (req, res, next) =&gt; {
      var filePath = path.resolve("./datasource", req.query.path);
      fs.readFile(filePath, "utf8", (err, data) =&gt; {
          processData(data, (err, processed) =&gt; {
              res.json(processed);
          });
      });
  });
  </code></pre>
  
  <p>I stripped out error handling for clarity. The problem with this is that one could call the url <code>/api?path=../../../etc/passwd</code>, and that would leak information from the server itself. I would like this api not to process files outside of the <code>./datasource</code> folder. I think I could use some customized implementation of <code>path.resolve</code>, which does not escape the parent, but it looks like to me there is no such functionality in the <code>path</code> module. Some examples I thought of:</p>
  
  <pre><code>saferesolve("./datasource", "a/b") === "./datasource/a/b"
  saferesolve("./datasource", "a/b/../c") === "./datasource/a/c"
  saferesolve("./datasource", "../..") === "./datasource"
  saferesolve("./datasource", "../../a/b") === "./datasource/a/b"
  saferesolve("./datasource", "../../a/b/..") === "./datasource/a"
  </code></pre>
  
  <p>Any ideas how to accomplish this without reinventing the whole <code>path</code> module?</p>