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 對象

參考文檔

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