normalize:
const {normalize}=require('path'); // 规范化给定的path console.log(normalize('user//local')); console.log(normalize('user/../local/bin')); //userlocal //localin
join:
// 拼接路径 const {join}=require('path'); console.log(join('/user','local','bin/')); // userlocalin
resolve:
// 把相对路径解析成绝对路径 console.log(join('/user','local','bin/')); const {resolve}=require('path'); userlocalin
basename, dirname, extname:
// 与名称有关 const {basename, dirname, extname}=require('path'); const filePath='user/local/bin/no.txt'; console.log(basename(filePath)); console.log(dirname(filePath)); console.log(extname(filePath)); // no.txt 文件名 // user/local/bin 路径名 // .txt 拓展名
parse,format:
// parse:分析路径 format:聪一个对象返回一个路径字符串,一般在需要修改路径的某个属性时才会用到 const {parse,format}=require('path'); const filePath='/user/local/bin/no.txt'; const ret=parse(filePath); console.log(ret); // { root: '/', dir: '/user/local/bin', base: 'no.txt', ext: '.txt', name: 'no' } console.log(format(ret)); // /user/local/bin o.txt
paths:
const path=require('path'); console.log('__dirname',__dirname); console.log('process.cwd()',process.cwd()); console.log('./',path.resolve('./')); // 执行前先 cd ../ 然后执行命令 // __dirname C:Users estDesktop ode // process.cwd() C:Users estDesktop // ./ C:Users estDesktop // __filename、__dirname 总是返回文件的绝对路径 // process.cwd() 总是返回执行node命令所在文件夹 // ./ 在require方法中相对当前文件所在文件夹,在其他地方process.cwd()一样