path.relative
时间: 2023-09-11 21:04:08 浏览: 41
(path, base)
The `path.relative()` method in Node.js determines the relative path from one absolute path to another absolute path, based on a given base path. It returns a string representing the relative path between the two provided paths.
Parameters:
- `path`: A string representing the first absolute path.
- `base`: A string representing the second absolute path.
Returns:
- A string representing the relative path from `base` to `path`.
Example:
```javascript
const path = require('path');
const path1 = '/Users/user/dir/subdir/file.txt';
const path2 = '/Users/user/otherdir/file.txt';
const base = '/Users/user/';
const relativePath = path.relative(base, path1);
console.log(relativePath); // Output: dir/subdir/file.txt
const relativePath2 = path.relative(base, path2);
console.log(relativePath2); // Output: ../otherdir/file.txt
```
In the example above, `path.relative()` is used to determine the relative paths between two absolute paths (`path1` and `path2`) and a base path (`base`). The resulting paths are printed to the console.