How do I find out whether a file is within a directory with Node.js?

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 have asynchronous versions, see fs module.

fs.realpathSync and fs.statSyncwill throw if the path does not exist.


I suggest this:

const path = require('path')

function isWithin(outer, inner) {
    const rel = path.relative(outer, inner);
    return !rel.startsWith('../') && rel !== '..';
}

It uses path.relative to compute the path of inner relative to outer. If it's not contained, the first component of the resulting path will be .., so that's what we check for.