0.0.0 • Published 6 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/..') // falseInstall
> npm install path-contains-path
# or
> yarn add path-contains-pathUse
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): booleanancestor– path representing a directorydescendant- path representing another file/directory that you want to check is a descendant ofancestorpath(optional) - the Node.jspathmodule of your choice. Defaults torequire('path').- In rare situations you might want to override this with e.g.
require('path').posixorrequire('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.resolveto 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-pathif 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
6 years ago