nodejs模块path

版权声明:本文为个人知识整理,欢迎指正、交流、转载。 https://blog.csdn.net/u014711094/article/details/80444599
  • sep delimiter
// Provides platform-specific path segment separator
path.sep
// backward slash '\' on windows. forward slash '/' on POSIX.

// Provides platform-specific path delimiter
path.delimiter
// semicolon ';' for windows. colon ':' for POSIX.

process.env.PATH.split(path.delimeter)
// ['C:\\windows', ...]
  • dirname() basename() extname()
const {dirname, basename, extname} = path

let f1 = 'G:\\temp\\index.js'
let f2 = 'G:\\temp\\'
let f3 = '../index.js'
let f4 = 'index.js'

dirname(f1)     // 'G:\\temp'
dirname(f2)     // 'G:\\'
dirname(f3)     // '..'
dirname(f4)     // '.'
dirname('../../index.js')   // '../..'

// Returns the last portion of a path. 
basename(f1)    // 'index.js'
basename(f2)    // 'temp'

basename(f1, '.js')     // index
basename(f1, 'js')      // index.
basename(f1, 'x.js')    // inde
basename(f1, 'ss')      // index.js

extname(f1)     // '.js'
extname(f2)     // ''
extname('index.')   // '.'
extname('index.js.html')    // '.html'
extname('.index')   // ''
extname('.index.js')    // '.js'
  • parse() format()
const {parse, format} = path

// 解析string为pathObject,要求类型正确
parse(f1)
// {root: 'G:\\', dir: 'G:\\temp', base: 'index.js', ext: '.js', name: 'index'}
parse(f2)
// {root: 'G:\\', dir: 'G:\\', base: 'temp', ext: '', name: 'temp'}
parse(f3)
// {root: '', dir: '..', base: 'index.js', ext: '.js', name: 'index'}

// 将pathObject格式化为string,要求类型正确
// 有dir会忽略root,有base会忽略ext和name
let o1 = {dir: 'a.js/', ext: '.html', name: 'index'}

// 字符串拼接
format(o1)  // a.js/\index.html
  • isAbsolute()
const {isAbsolute} = path

isAbsolute('g:\\temp')      // true
isAbsolute('..')            // false

isAbsolute('temp')          // false
isAbsolute('/temp')         // true
isAbsolute('\\temp')        // true
  • join() normalize() resolve() relative()
const {join, normalize, resolve, relative} = path

join()  // '.'
// 相对路径会解析,多余的slash和backslash会忽略
join('g:/', 'a////b\\\\c', '', '.', 'd/', '..', 'index.js')
//  g:\a\b\c\index.js

// normalize()接收string, 效果和join()相同
normalize('g:\a////b\\\\c/./d/../.\\index.js')
// g:a\b\c\index.js
normalize()     // 报错,参数不能为undefined

// 当前目录g:\a\b\c\index.js,从当前目录,从左到右解析
resolve()   // g:\a\b\c
resovle('../..\\', '../d\\\\b/index.js', 'some.html')
// g:\d\b\index.js\some.html

// relative(from, to)可理解为from和to的绝对路径的差
relative('', '..')      // ..
relative('../a/b/index.js', '../c/index.js')
// ../../c/index.js

参考:https://nodejs.org/dist/latest-v10.x/docs/api/path.html

猜你喜欢

转载自blog.csdn.net/u014711094/article/details/80444599