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

相关推荐
10年前端老司机6 分钟前
Promise 常见面试题(持续更新中)
前端·javascript
麦麦鸡腿堡29 分钟前
Java的动态绑定机制(重要)
java·开发语言·算法
时间之里30 分钟前
【c++】:Lambda 表达式介绍和使用
开发语言·c++
Tiger_shl42 分钟前
C# 预处理指令 (# 指令) 详解
开发语言·c#
@Kerry~1 小时前
phpstudy .htaccess 文件内容
java·开发语言·前端
CRMEB系统商城1 小时前
CRMEB多商户系统(PHP)v3.3正式发布,同城配送上线[特殊字符]
java·开发语言·小程序·php
sali-tec2 小时前
C# 基于halcon的视觉工作流-章45-网格面划痕
开发语言·算法·计算机视觉·c#
一壶浊酒..2 小时前
python 爬取百度图片
开发语言·python·百度
机器视觉知识推荐、就业指导2 小时前
C语言中的预编译是什么?何时需要预编译?
c语言·开发语言
·心猿意码·2 小时前
C++智能指针解析
开发语言·c++