nodejs模組path
阿新 • • 發佈:2018-11-10
- 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