node.js的path模块提供了
操作路径的功能,本文记录几个常用的API。
1.Path模块常用的API
| API | 说明 |
|---|---|
| path.resolve | 拼接规范的绝对路径(最常用) |
| path.sep | 获取操作系统的路径分隔符 |
| path.parse | 解析路径并返回对象 |
| path.basename | 获取路径的基础名称 |
| path. | 获取路径的目录名 |
| path. | 获取路径的扩展名 |
2.path.resolve
const fs = require('fs');
console.log(__dirname+'/index.html') //C:\Users\***\Desktop\每日精进\node.js\noteJs/index.html
//使用resolve
console.log(path.resolve(__dirname,'./index.html')) //C:\Users\***\Desktop\每日精进\node.js\noteJs\index.html/
console.log(path.resolve(__dirname,'index.html')) //同上 C:\Users\***\Desktop\每日精进\node.js\noteJs\index.html/
console.log(path.resolve(__dirname,'/index.html')) // 第二个参数/index.html表示绝对路径 输出:C:\index.html
console.log(path.resolve(__dirname,'/index.html','./test')) // C:\index.html\test
3.path.sep
console.log(path.sep) // windows的分隔符是\ linux的分隔符是/
4.path.parse
console.log(__filename) //C:\Users\***\Desktop\****\node.js\noteJs\9path.js
//取到__filename给到str,__filename可看为‘全局变量’,保存的是文件的绝对路径
let str = 'C:\\Users\\***\\Desktop\\****\\node.js\\noteJs\\9path.js' //注意要转义
console.log(path.parse(str))
//输出结果如下:
{
root: 'C:\\', //根目录
dir: 'C:\\Users\\***\\Desktop\\****\\node.js\\noteJs', //所在文件夹绝对路径
base: '9path.js', //文件名
ext: '.js', //文件扩展名
name: '9path' //文件名
}
5.path.basename
let str = 'C:\\Users\\***\\Desktop\\****\\node.js\\noteJs\\9path.js' //注意要转义
console.log(path.basename(str)) //9path.js
6.path.dirname
let str = 'C:\\Users\\***\\Desktop\\****\\node.js\\noteJs\\9path.js' //注意要转义
console.log(path.dirname(str)) //C:\Users\***\Desktop\****\node.js\noteJs
7.path.extname
let str = 'C:\\Users\\***\\Desktop\\****\\node.js\\noteJs\\9path.js' //注意要转义
console.log(path.extname(str)) //.js
【写在后面】:最常用的就是path.resolve()了,这个在前端项目的一些配置文件中常见到。最后三个方法其实就是取path.parse()对象中的单个属性值。path模块的学习内容较少,但我还没有验证过是否真的掌握这些就足够了,为了保证整体学习节奏,打算先继续向下一个模块出发了。Go Go GO!
学习视频连接: https://b23.tv/rXRE9Cx。
emm...貌似有了几年工作经验,学习的时候,融会贯通的能力到底还是提高了不少哇~