Determine if a path is subdirectory of another in Node.js

Let Node itself do the work.

const path = require('path');
const relative = path.relative(parent, dir);
return relative && !relative.startsWith('..') && !path.isAbsolute(relative);

It does normalisation for you as well.

const path = require('path');

const tests = [
  ['/foo', '/foo'],
  ['/foo', '/bar'],
  ['/foo', '/foobar'],
  ['/foo', '/foo/bar'],
  ['/foo', '/foo/../bar'],
  ['/foo', '/foo/./bar'],
  ['/bar/../foo', '/foo/bar'],
  ['/foo', './bar'],
  ['C:\\Foo', 'C:\\Foo\\Bar'],
  ['C:\\Foo', 'C:\\Bar'],
  ['C:\\Foo', 'D:\\Foo\\Bar'],
];

tests.forEach(([parent, dir]) => {
    const relative = path.relative(parent, dir);
    const isSubdir = relative && !relative.startsWith('..') && !path.isAbsolute(relative);
    console.log(`[${parent}, ${dir}] => ${isSubdir} (${relative})`);
});

Works on Windows across drives too.

[/foo, /foo] => false ()
[/foo, /bar] => false (..\bar)
[/foo, /foobar] => false (..\foobar)
[/foo, /foo/bar] => true (bar)
[/foo, /foo/../bar] => false (..\bar)
[/foo, /foo/./bar] => true (bar)
[/bar/../foo, /foo/bar] => true (bar)
[/foo, ./bar] => false (..\Users\kozhevnikov\Desktop\bar)
[C:\Foo, C:\Foo\Bar] => true (Bar)
[C:\Foo, C:\Bar] => false (..\Bar)
[C:\Foo, D:\Foo\Bar] => false (D:\Foo\Bar)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)