path 用于文件路徑操作
官方文檔
- https://nodejs.org/api/path.html
一個不錯的解釋
┌─────────────────────┬────────────┐
│ dir │ base │
├──────┬ ├──────┬─────┤
│ root │ │ name │ ext │
" / home/user/dir / file .txt "
└──────┴──────────────┴──────┴─────┘
示例文章來源:http://www.zghlxwxcb.cn/news/detail-643470.html
const path = require('path')
const filename = '/user/bin/file.js'
// 判斷 path 是否為絕對路徑
console.log(path.isAbsolute(filename))
// true
// 解析文件路徑
console.log(path.parse(filename))
// {
// root: '/',
// dir: '/user/bin',
// base: 'file.js',
// ext: '.js',
// name: 'file'
// }
// 轉(zhuǎn)為字符串
console.log(
path.format({
root: '/',
dir: '/user/bin',
base: 'file.js',
ext: '.js',
name: 'file',
})
)
// /user/bin/file.js
// 獲取文件名
// 返回文件類型
console.log(path.basename(filename))
// file.js
// 不返回文件類型
console.log(path.basename(filename, '.js'))
// file
// 獲取目錄層級
console.log(path.dirname(filename))
// /user/bin
// 獲取擴(kuò)展名
console.log(path.extname(filename))
// .js
// 連接路徑
console.log(path.join('dir1', 'dir2', 'file.js'));
// dir1/dir2/file.js
// 將路徑進(jìn)行標(biāo)準(zhǔn)化
console.log(path.normalize('dir1/dir2/../file.js'));
// dir1/file.js
// 返回相對路徑
console.log(path.relative('dir1/dir2', 'file.js'))
// ../../file.js
// 返回絕對路徑
console.log(path.resolve('dir1', 'dir2', 'file.js'))
// /Users/tom/workspace/dir1/dir2/file.js
// 路徑分隔符
console.log(path.sep);
// /
參考文章
node之Path介紹文章來源地址http://www.zghlxwxcb.cn/news/detail-643470.html
到了這里,關(guān)于Node.js:path文件路徑操作模塊的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!