path
为 Node.js 常用的内置 npm 模块,主要为了更加方便的处理文件与目录路径,通常可通过 const path = require('path')
引用。
Windows vs. POSIX
POSIX 称之为可移植操作系统接口(Portable Operating System Interface of UINX,POSIX),定义了操作系统为应用程序提供的了统一的接口标准,具体想了解的可自行 Google,在这可以简单把其认为是 uinx。
path
模块根据 node 应用程序所在的系统环境不同而呈现不同的默认操作。像在 Windows 操作系统中,path
会根据 Windows 的路径规范来操作。
在 POSIX 上:
path.basename('C:\\temp\\myfile.html');
// returns: 'C:\\temp\\myfile.html'
在 Windows 上:
path.basename('C:\\temp\\myfile.html');
// returns: 'myfile.html'
为了能够在以上两个系统中呈现一致的操作可在两系统中都执行:
path.win32.basename('C:\\temp\\myfile.html') // 呈现 Windows的效果
// 或者 path.posix.basename('C:\\temp\\myfile.html') //呈现 POSIX 的效果
注意:在 Windows 中,path
在有且仅有一个驱动盘的时候需要注意带反斜杠 \\
与不带的区别,比如 path.resolve('C:\\')
与 path.resolve('C:')
是有可能不一样的,具体可见 MSDN
path.basename(path[,ext])
- 形参
path
: string 类型ext
: string 类型,可选项,表示文件类型
- 返回
- string 类型,
path
的最后一部分,与 Uinx 命令basename
返回的结果类似。
- string 类型,
举例:
path.basename('/foo/bar/baz/asdf/quux.html');
// Returns: 'quux.html'
path.basename('/foo/bar/baz/asdf/quux.html', '.html');
// Returns: 'quux', '.html' 中的 '.' 不能省略
报错情况: path
不是 string 类型, ext
给出但不是 string 类型
path.delimiter
提供不同系统对应的路径分隔符:
- Windows:
;
- POSIX:
:
举例:
- 在 POSIX 中:
console.log(process.env.PATH);
// Prints: '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin'
process.env.PATH.split(path.delimiter);
// Returns: ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin']
- 在 Windows 中:
console.log(process.env.PATH);
// Prints: 'C:\Windows\system32;C:\Windows;C:\Program Files\node\'
process.env.PATH.split(path.delimiter);
// Returns ['C:\\Windows\\system32', 'C:\\Windows', 'C:\\Program Files\\node\\']
path.dirname(path)
- 形参:
path
: string 类型,路径。
- 返回:string 类型,
path
的所在目录,与 Uinx 命令dirname
返回的结果类似。
比如: