一.函数介绍
1.path.join()
//path.join('要拼接的文件地址')
const pathStr = path.join('a', 'b/c', '../')
console.log(pathStr) // 输出/a/b
2.path.basename()
//返回输入路径的最后一项
//path.basename(参数一,'参数二')
//参数一(必填):当前想要返回最后一项地址的文件路径
//参数二(选填):想要取消的字符串,若没有与之相匹配的字符串则不取消
const path = require('path')
const tempPath = './ab/c/d/index.exe'
let lastPath = path.basename(tempPath)
console.log(lastPath) //输出index.exe
lastPath = path.basename(tempPath, '.exe')
console.log(lastPath) //输出index
3.path.exdname()
//返回输入路径的最后一项扩展名
//path.extname(参数一)
//参数一(必填):当前想要返回扩展名地址的文件路径
const path = require('path')
const tempPath = './ab/c/d/index.exe'
let lastPath = path.extname(tempPath)
console.log(lastPath) //输出.exe
二.注意事项
1.路径拼接
在使用路径的时候传统方法我们是使用+进行拼接,但是现在我们学习了path.join()这个方法,所以我们现在统一使用path.join()进行拼接。
传统拼接会造成的问题
const fs = require('fs')
fs.readFile(__dirname + '../files/1.txt', 'utf8', (err, dataStr) => {
if(err){
console.log('读取文件失败', err)
}else{
console.log('读取文件成功', dataStr)
}
})
因此为了防止本问题发生,我们需要用path.join()来进行地址的拼接
const fs = require('fs')
const path = require('path')
fs.readFile(path.join(__dirname, '../files/1.txt'), 'utf8', (err, dataStr) => {
if(err){
console.log('读取文件失败', err)
}else{
console.log('读取文件成功', dataStr)
}
})