常用path方法
1
2
3
4
5
6
7
8
9
10
11
12
13
const path = require('path');
console.log(path.sep) //获取操作系统的路径分隔符
console.log(path.delimiter) //获取操作系统的环境变量分隔符
console.log(path.basename(__filename)) //获取当前文件名,包含扩展名
console.log(path.basename(__filename,'.js')) //获取当前文件名,不包含扩展名
console.log(path.dirname(__filename)) //获取当前路径
console.log(__dirname) //获取当前路径
console.log(__filename) //获取当前文件的绝对路径
console.log(path.extname(__filename)) //获取当前文件扩展名
console.log(path.parse(__filename)) //将文件路径解析为js对象返回
console.log(path.isAbsolute(__filename)) //判断是否绝对路径
console.log(path.join(__dirname,file.txt)) //拼接路径,如在下一级目录,依次添加目录名参数,以操作系统路径分隔符拼接
console.log(path.resolve('f:','fb','cd')) //拼接路径,第一个参数是盘符,不写默认拼接当前js文件所在盘符
路径字符串和js对象转换
1
2
3
4
5
6
7
8
9
10
11
12
console.log(path.parse(__filename))    
/*
将文件路径字符串解析为js对象返回
返回结果:
{
root: 'C:\\',
dir: 'C:\\Users\\lujunjie\\WebstormProjects\\untitled\\day1',
base: 'path.js',
ext: '.js',
name: 'path'
}
*\
1
2
3
4
5
6
7
8
9
var pathobj = {
root: 'C:\\',
dir: 'C:\\Users\\lujunjie\\WebstormProjects\\untitled\\day1',
base: 'path.js',
ext: '.js',
name: 'path'
}
console.log(path.format(pathobj))
//输出结果:C:\Users\lujunjie\WebstormProjects\untitled\day1\path.js