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介绍

相关推荐
烟雨江南aabb15 小时前
Python第六弹:python爬虫篇:什么是爬虫
开发语言·爬虫·python
沐知全栈开发16 小时前
Servlet 文件上传详解
开发语言
一只小小Java16 小时前
Echarts单表多图实现
前端·javascript·echarts
跟着珅聪学java16 小时前
Element UI 的 Tabs 标签页开发教程
javascript·vue.js·elementui
濮水大叔16 小时前
告别 Django Admin!这个 NodeJS 全栈框架让你在 DTO 中直接配置 Table/Form 渲染
前端·typescript·node.js
竹林81816 小时前
用Viem替换ethers.js:一次合约交互的"减负"实战,我总算把TypeScript类型搞明白了
前端·javascript
basketball61616 小时前
C++ iostream 完全指南:从 cin/cout 到流式编程的奥秘
开发语言·c++
SilentSamsara16 小时前
运算符重载:让自定义对象支持 +、[]、in 操作
开发语言·python·算法·青少年编程·pycharm
threelab16 小时前
Three.js 3D 热力图效果 | 三维可视化 / AI 提示词
开发语言·前端·javascript·人工智能·3d·着色器
Royzst16 小时前
图书管理案例
java·开发语言