What is path-is-inside?
The path-is-inside npm package is used to determine if one path is inside another path. This can be useful for ensuring that a file is within a certain directory structure, for security checks to prevent directory traversal attacks, or for validating file locations in a project.
What are path-is-inside's main functionalities?
Check if a path is inside another path
This feature allows you to check if one path is contained within another path. It returns a boolean value indicating the result.
const pathIsInside = require('path-is-inside');
let inside = pathIsInside('/the/path', '/the'); // true
let notInside = pathIsInside('/the/path', '/another/path'); // false
Other packages similar to path-is-inside
is-path-inside
This package provides similar functionality to path-is-inside, allowing you to check if one path is inside another. It is a lightweight package with minimal dependencies.
is-subdir
is-subdir is another package that checks if a directory is a subdirectory of another. It compares to path-is-inside by offering a similar check but may have different implementation details or dependencies.
Is This Path Inside This Other Path?
It turns out this question isn't trivial to answer using Node's built-in path APIs. A naive indexOf
-based solution will fail sometimes on Windows, which is case-insensitive (see e.g. isaacs/npm#4214). You might then think to be clever with path.resolve
, but you have to be careful to account for situations whether the paths have different drive letters, or else you'll cause bugs like isaacs/npm#4313. And let's not even get started on trailing slashes.
The path-is-inside package will give you a robust, cross-platform way of detecting whether a given path is inside another path.
Usage
Pretty simple. First the path being tested; then the potential parent. Like so:
var pathIsInside = require("path-is-inside");
pathIsInside("/x/y/z", "/x/y")
pathIsInside("/x/y", "/x/y/z")
OS-Specific Behavior
Like Node's built-in path module, path-is-inside treats all file paths on Windows as case-insensitive, whereas it treats all file paths on *-nix operating systems as case-sensitive. Keep this in mind especially when working on a Mac, where, despite Node's defaults, the OS usually treats paths case-insensitively.
In practice, this means:
pathIsInside("C:\\X\\Y\\Z", "C:\\x\\y")
pathIsInside("/X/Y/Z", "/x/y")