path会根据操作的系统的不同自动获取对应的系统的文件路径格式。具体可查看文档http://nodejs.cn/api/path.html#path_path_normalize_path。下面我总结几个比较常用的api:
1.path.normalize()
normalize方法会规范给定的路径
// 引入方式
const {normalize} = require('path')
console.log(normalize('/usr//local/bin'))
console.log(normalize('/usr//local/../bin'))
/*
运行结果是
usr//local/bin
usr//bin
*/
2.path.join()
join方法用来拼接多个路径,它也会自动规范拼接的路径,并且也支持normalize的书写方式
const {join} = require("path");
console.log(join('/usr','local','//bin'))
console.log(join('/usr','../local','bin'))
/*
输出结果
/usr/local/bin
/local/bin
*/
3.path.resolve()
方法将路径或路径片段的序列解析为绝对路径。
const {resolve} = require("path");
console.log(resolve('./'))
4.basename, extname, dirname方法
basename方法返回 path
的最后一部分
extname方法返回 path
的扩展名
dirname方法返回 返回 path
的目录名
const {basename, extname, dirname} = require("path");
const filePath = '/usr/local/bin/index.html';
console.log(basename(filePath));
console.log(extname(filePath));
console.log(dirname(filePath));
/*
index.html
.html
/usr/local/bin
*/
5.parse, format方法
parse 方法返回一个对象,其属性表示 path
的重要元素
format
方法从对象返回路径字符串
const {parse, format} = require("path");
let filePath = '/usr/local/bin/index.html';
filePath = parse(filePath)
filePath.base = 'aaa.html'
console.log(filePath)
filePath = format(filePath)
console.log(filePath)
/*
打印结果
{ root: '/',
dir: '/usr/local/bin',
base: 'aaa.html',
ext: '.html',
name: 'index' }
/usr/local/bin/aaa.html
*/