path.parse(path)
path.parse()
方法会返回一个对象,其属性表示 path
的有效元素。
尾部的目录分隔符会被忽略,参见 path.sep
。
返回的对象具有以下属性:
例如,在 POSIX 上:
path.parse('/目录1/目录2/文件.txt');
// 返回:
// { root: '/',
// dir: '/目录1/目录2',
// base: '文件.txt',
// ext: '.txt',
// name: '文件' }
┌─────────────────────┬────────────┐
│ dir │ base │
├──────┬ ├──────┬─────┤
│ root │ │ name │ ext │
" / 目录1/目录2 / 文件 .txt "
└──────┴──────────────┴──────┴─────┘
("" 行中的所有空格均可忽略。它们纯粹是用于格式化。)
在 Windows 上:
path.parse('C:\\目录1\\目录2\\文件.txt');
// 返回:
// { root: 'C:\\',
// dir: 'C:\\目录1\\目录2',
// base: '文件.txt',
// ext: '.txt',
// name: '文件' }
┌─────────────────────┬────────────┐
│ dir │ base │
├──────┬ ├──────┬─────┤
│ root │ │ name │ ext │
" C:\ 目录1\目录2 \ 文件 .txt "
└──────┴──────────────┴──────┴─────┘
("" 行中的所有空格均可忽略。它们纯粹是用于格式化。)
如果 path
不是字符串,则抛出 TypeError
。
The path.parse()
method returns an object whose properties represent
significant elements of the path
. Trailing directory separators are ignored,
see path.sep
.
The returned object will have the following properties:
For example, on POSIX:
path.parse('/home/user/dir/file.txt');
// Returns:
// { root: '/',
// dir: '/home/user/dir',
// base: 'file.txt',
// ext: '.txt',
// name: 'file' }
┌─────────────────────┬────────────┐
│ dir │ base │
├──────┬ ├──────┬─────┤
│ root │ │ name │ ext │
" / home/user/dir / file .txt "
└──────┴──────────────┴──────┴─────┘
(All spaces in the "" line should be ignored. They are purely for formatting.)
On Windows:
path.parse('C:\\path\\dir\\file.txt');
// Returns:
// { root: 'C:\\',
// dir: 'C:\\path\\dir',
// base: 'file.txt',
// ext: '.txt',
// name: 'file' }
┌─────────────────────┬────────────┐
│ dir │ base │
├──────┬ ├──────┬─────┤
│ root │ │ name │ ext │
" C:\ path\dir \ file .txt "
└──────┴──────────────┴──────┴─────┘
(All spaces in the "" line should be ignored. They are purely for formatting.)
A TypeError
is thrown if path
is not a string.