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

相关推荐
3GPP仿真实验室23 分钟前
【Matlab源码】6G候选波形:OFDM-IM 增强仿真平台 DM、CI
开发语言·matlab·ci/cd
devmoon27 分钟前
在 Polkadot 上部署独立区块链Paseo 测试网实战部署指南
开发语言·安全·区块链·polkadot·erc-20·测试网·独立链
lili-felicity27 分钟前
CANN流水线并行推理与资源调度优化
开发语言·人工智能
沐知全栈开发28 分钟前
CSS3 边框:全面解析与实战技巧
开发语言
island131437 分钟前
CANN GE(图引擎)深度解析:计算图优化管线、内存静态规划与异构 Stream 调度机制
c语言·开发语言·神经网络
曹牧42 分钟前
Spring Boot:如何在Java Controller中处理POST请求?
java·开发语言
浅念-1 小时前
C++入门(2)
开发语言·c++·经验分享·笔记·学习
WeiXiao_Hyy1 小时前
成为 Top 1% 的工程师
java·开发语言·javascript·经验分享·后端
User_芊芊君子1 小时前
CANN010:PyASC Python编程接口—简化AI算子开发的Python框架
开发语言·人工智能·python
Max_uuc1 小时前
【C++ 硬核】打破嵌入式 STL 禁忌:利用 std::pmr 在“栈”上运行 std::vector
开发语言·jvm·c++