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

相关推荐
m0_380743872 小时前
C++中的freopen的用法实例详解
开发语言·c++
Escalating_xu3 小时前
【Python】基础语法(1):常量、变量、类型、输入输出与运算符
开发语言·python
jimy13 小时前
polymorph.cpp里面的“析构函数、智能指针”问题
开发语言·c++
m0_380743873 小时前
PHP 8.3 缓存清除不生效怎么排查
开发语言·php
朝朝辞暮i4 小时前
C++ 第 6 课:switch —— 多状态选择
开发语言·c++·算法
小凡geo4 小时前
本地商家 GEO:用脚本一键生成 FAQPage 结构化数据,让 AI 切片更稳
开发语言·人工智能·python·microsoft·搜索引擎·ai
朝朝辞暮i4 小时前
C++ 第 4 课:if / else —— 让程序自己做决定
开发语言·c++
波力海苔夹心脆6754 小时前
C# 值类型与引用类型详解:存储位置、赋值机制、参数传递、相等比较、装箱拆箱与常见陷阱
开发语言·jvm·经验分享·笔记·c#·.net
m0_380743874 小时前
Qt中导航栏实现的详细指南
开发语言·c++
mhmh1234 小时前
Python 对象模型与数据模型:魔术方法、描述符与元类深度解析
开发语言·python