Node.js:path文件路径操作模块

path 用于文件路径操作

官方文档

一个不错的解释

复制代码
 ┌─────────────────────┬────────────┐
 │          dir        │    base    │
 ├──────┬              ├──────┬─────┤
 │ root │              │ name │ ext │
 "  /    home/user/dir / file  .txt "
 └──────┴──────────────┴──────┴─────┘

示例

js 复制代码
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'
// }



// 转为字符串
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

// 获取扩展名
console.log(path.extname(filename))
// .js

// 连接路径
console.log(path.join('dir1', 'dir2', 'file.js'));
// dir1/dir2/file.js

// 将路径进行标准化
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介绍

相关推荐
三巧26 分钟前
纯CSS吃豆人(JS仅控制进度)
javascript·css·html
软件技术NINI43 分钟前
html css js网页制作成品——HTML+CSS+js美甲店网页设计(5页)附源码
javascript·css·html
JAVA学习通1 小时前
JAVA多线程(8.0)
java·开发语言
Luck_ff08101 小时前
【Python爬虫详解】第四篇:使用解析库提取网页数据——BeautifuSoup
开发语言·爬虫·python
天天扭码1 小时前
从数组到对象:JavaScript 遍历语法全解析(ES5 到 ES6 + 超详细指南)
前端·javascript·面试
学渣676561 小时前
什么时候使用Python 虚拟环境(venv)而不用conda
开发语言·python·conda
拉不动的猪1 小时前
前端开发中常见的数据结构优化问题
前端·javascript·面试
想睡hhh1 小时前
c++STL——stack、queue、priority_queue的模拟实现
开发语言·c++·stl
小鹿鹿啊1 小时前
C语言编程--14.电话号码的字母组合
c语言·开发语言·算法
Sunlight_7771 小时前
第六章 QT基础:6、QT的Qt 时钟编程
开发语言·qt·命令模式