node之Path介绍

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 返回的结果类似。

举例:

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 返回的结果类似。

比如:

path.dirname('/foo/bar/baz/asdf/quux');
// Returns: '/foo/bar/baz/asdf'

报错情况: path 不是 string 类型

path.extname(path)

  • 形参:
    • path : string 类型,路径。
  • 返回:string 类型,path 的所对应的扩展名。

举例:

path.extname('index.html');
// Returns: '.html'

path.extname('index.coffee.md');
// Returns: '.md'

path.extname('index.');
// Returns: '.'

path.extname('index');
// Returns: ''

path.extname('.index');
// Returns: ''

path.extname('.index.md');
// Returns: '.md'

报错情况: path 不是 string 类型

path.format(pathObject)

  • pathObject

    • dir string 类型
    • root string 类型
    • base string 类型
    • name string 类型
    • ext string 类型
  • Returns: string 类型,将 pathObject 转换成 path

与之相关的逆操作有 path.parse()

注意pathObject 属性值有冲突时,请遵循以下属性优先级:

  • pathObject.dir 有效时, pathObject.root 会被忽略
  • pathObject.base 存在时,pathObject.extpathObject.name 会被忽略。

举例:

在 POSIX 中

// If `dir`, `root` and `base` are provided,
// `${dir}${path.sep}${base}`
// will be returned. `root` is ignored.
path.format({
  root: '/ignored',
  dir: '/home/user/dir',
  base: 'file.txt'
});
// Returns: '/home/user/dir/file.txt'

// `root` will be used if `dir` is not specified.
// If only `root` is provided or `dir` is equal to `root` then the
// platform separator will not be included. `ext` will be ignored.
path.format({
  root: '/',
  base: 'file.txt',
  ext: 'ignored'
});
// Returns: '/file.txt'

// `name` + `ext` will be used if `base` is not specified.
path.format({
  root: '/',
  name: 'file',
  ext: '.txt'
});
// Returns: '/file.txt'

在 Windows 中

path.format({
  dir: 'C:\\path\\dir',
  base: 'file.txt'
});
// Returns: 'C:\\path\\dir\\file.txt'

path.isAbsolute(path)

  • path string 类型
  • Returns: Boolean 类型,判断 path 是否为绝对路径,如果是空字符串,则会返回 false

举例

POSIX:

path.isAbsolute('/foo/bar'); // true
path.isAbsolute('/baz/..');  // true
path.isAbsolute('qux/');     // false
path.isAbsolute('.');        // false

Windows:

path.isAbsolute('//server');    // true
path.isAbsolute('\\\\server');  // true
path.isAbsolute('C:/foo/..');   // true
path.isAbsolute('C:\\foo\\..'); // true
path.isAbsolute('bar\\baz');    // false
path.isAbsolute('bar/baz');     // false
path.isAbsolute('.');           // false

报错情况: path 不是 string 类型

path.join([...paths])

  • ...paths string类型,一系列的路径
  • Returns: string 类型,使用系统对应的路径分隔符将这一系列路径连接到一起。

举例:

path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');
// Returns: '/foo/bar/baz/asdf'

path.join('foo', {}, 'bar');
// Throws 'TypeError: Path must be a string. Received {}'

报错情况: 这一系列路径中存在不是 string 类型的元素。

path.normalize(path)

将路径进行标准化

  • path string 类型
  • Returns: string 类型

可以解析路径中的 ‘…’ 和 ‘.’ 特殊字符串

举例

POSIX:

path.normalize('/foo/bar//baz/asdf/quux/..');
// Returns: '/foo/bar/baz/asdf'

Windows:

path.normalize('C:\\temp\\\\foo\\bar\\..\\');
// Returns: 'C:\\temp\\foo\\'

报错情况:path 不是 string 类型

path.parse(path)

  • path string 类型。
  • Returns: Object 类型,与 path.format() 对应。

举例

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.)*/

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.)*/

报错情况: path 不是 string 类型

path.posix

提供 POSIX 对应的 path 对象

path.relative(from, to)

  • from string 类型,基准路径
  • to string 类型,目标路径
  • Returns: string 类型 ,返回相对路径。目标路径相对基准路径的相对路径。

注意:

  • 如果 fromto 相同,则返回空字符串。
  • 如果 fromto 为空字符串,则返回当前路径。

举例

// POSIX
path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb');
// Returns: '../../impl/bbb'

//Windows
path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb');
// Returns: '..\\..\\impl\\bbb'

报错情况: fromto 不是 string 类型

path.resolve([...paths])

  • ...paths string类型,一系列的路径
  • Returns: string 类型,解析一系列的路径成绝对路径。

注意:

  • 右向左 依次拼接。直到遇到第一个绝对路径形式的 path 才停止. 比如 path.resolve('/foo', '/bar', 'baz'). 从右向左一次解析,第一次遇到的绝对路径为 '/bar' ,所以不再继续向左拼接,及最终结果为 '/bar' + '/' + 'baz' = '/bar/baz' ,如实例 2
  • 如果这一系列路径中一个绝对路径都没有的话,则将当前路径作为绝对路径的基准。如实例 3
  • 空字符串会被忽略,如果 ...paths 都无效则会返回当前目录的绝对路径。
// 实例1 
path.resolve('/foo/bar', './baz');
// Returns: '/foo/bar/baz'

//实例 2
path.resolve('/foo/bar', '/tmp/file/');
// Returns: '/tmp/file'

// 实例3
path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif');
// If the current working directory is /home/myself/node,
// this returns '/home/myself/node/wwwroot/static_files/gif/image.gif'

报错情况: 这一系列路径中存在不是 string 类型的元素。

path.sep

提供不同系统对应的路径的 segment separator。

  • Windows: \
  • POSIX: /

举例

// POSIX
'foo/bar/baz'.split(path.sep);
// Returns: ['foo', 'bar', 'baz']

//Windows
'foo\\bar\\baz'.split(path.sep);
// Returns: ['foo', 'bar', 'baz']

注意:在 Windows 中,斜杠和反斜杠都可以作为 segment separator,但是在此 path 的方法中只能使用 反斜杠 \

path.toNamespacedPath(path)

  • path string 类型
  • Returns:

仅在 Windows 环境中有效

path.win32

提供 Windows 对应的 path 对象

参考文档

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章