path.basename(path[, ext])
path.basename()
方法会返回 path
的最后一部分,类似于 Unix 的 basename
命令。
尾部的目录分隔符会被忽略,参见 path.sep
。
path.basename('/目录1/目录2/文件.html');
// 返回: '文件.html'
path.basename('/目录1/目录2/文件.html', '.html');
// 返回: '文件'
尽管 Windows 通常以不区分大小写的方式处理文件名(包括文件扩展名),但是此函数不会这样。
例如, C:\\文件.html
和 C:\\文件.HTML
指向相同的文件,但是 basename
会将扩展名视为区分大小写的字符串:
path.win32.basename('C:\\文件.html', '.html');
// 返回: '文件'
path.win32.basename('C:\\文件.HTML', '.html');
// 返回: '文件.HTML'
如果 path
不是字符串、或给定了 ext
但不是字符串,则抛出 TypeError
。
The path.basename()
method returns the last portion of a path
, similar to
the Unix basename
command. Trailing directory separators are ignored, see
path.sep
.
path.basename('/foo/bar/baz/asdf/quux.html');
// Returns: 'quux.html'
path.basename('/foo/bar/baz/asdf/quux.html', '.html');
// Returns: 'quux'
Although Windows usually treats file names, including file extensions, in a
case-insensitive manner, this function does not. For example, C:\\foo.html
and
C:\\foo.HTML
refer to the same file, but basename
treats the extension as a
case-sensitive string:
path.win32.basename('C:\\foo.html', '.html');
// Returns: 'foo'
path.win32.basename('C:\\foo.HTML', '.html');
// Returns: 'foo.HTML'
A TypeError
is thrown if path
is not a string or if ext
is given
and is not a string.