0.0.0 • Published 5 years ago
dir-contains-path v0.0.0
dir-contains-path
Given two path strings, tells you if the first is an ancestor of the second.
Includes TypeScript typings.
// Absolute paths:
dirContainsPath('/foo', '/foo/bar/baz') // true
dirContainsPath('/foo', '/foo/bar/baz') // true
dirContainsPath('/foo', '/other/bar/baz') // false
dirContainsPath('/foo', '/foo/../other/bar/baz') // false
// Relative descendant paths are resolved from the ancestor
dirContainsPath('/foo', 'anything') // true
dirContainsPath('/foo', './anything') // true
dirContainsPath('/foo', '../foo/anything') // true
dirContainsPath('/foo', '../outside') // false
dirContainsPath('/foo', '../outside') // false
// When both args are effectively the same path: always false
dirContainsPath('/foo', '/foo') // false
dirContainsPath('/foo', '/foo/bar/..') // false
Install
> npm install path-contains-path
# or
> yarn add path-contains-path
Use
import { dirContainsPath } from 'dir-contains-path'
if (dirContainsPath('/foo', '/foo/bar/baz')) {
console.log('Yes it does')
}
API
dirContainsPath(ancestor: string, descendant: string, path?: path.PlatformPath): boolean
ancestor
– path representing a directorydescendant
- path representing another file/directory that you want to check is a descendant ofancestor
path
(optional) - the Node.jspath
module of your choice. Defaults torequire('path')
.- In rare situations you might want to override this with e.g.
require('path').posix
orrequire('path').win32
.
- In rare situations you might want to override this with e.g.
Errors
The function will throw an error:
- If either argument is a non-string, or an empty string.
- If the first argument (
ancestor
) is not an absolute path.- This is because it's unclear what the expectecd behaviour would be. You can always run the ancestor through
path.resolve
to make it absolute if that's what you want.
- This is because it's unclear what the expectecd behaviour would be. You can always run the ancestor through
Alternatives
Several other packages do the exact same thing:
- subdir
- is-subdir
Why make
dir-contains-path
if several packages already exist doing roughly the same thing?Mainly because I can never remember which way round the arguments go. For me,
dirContainsPath(a, b)
makes it unambiguous. Also because I wanted something stricter about strange input.
0.0.0
5 years ago