关于path.join,path.resolve的详细介绍

vue-cli生成的webpack配置中有大量path.resolve,path.join,有些模糊。网上查了好久,终于发现一篇讲的比较全面的文章

1.连接路径:path.join([path1][, path2][, ...])
path.join()方法可以连接任意多个路径字符串。要连接的多个路径可做为参数传入。

path.join()方法在接边路径的同时也会对路径进行规范化。例如:

var path = require('path'); 
//合法的字符串连接 
path.join('/foo', 'bar', 'baz/asdf', 'quux', '..') 
// 连接后 
'/foo/bar/baz/asdf' 

//不合法的字符串将抛出异常 
path.join('foo', {}, 'bar') 
// 抛出的异常 TypeError: Arguments to path.join must be strings'

2.路径解析:path.resolve([from ...], to)
path.resolve()方法可以将多个路径解析为一个规范化的绝对路径。其处理方式类似于对这些路径逐一进行cd操作,与cd操作不同的是,这引起路径可以是文件,并且可不必实际存在(resolve()方法不会利用底层的文件系统判断路径是否存在,而只是进行路径字符串操作)。例如:

path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile')

相当于

cd foo/bar
cd /tmp/file/
cd ..
cd a/../subfile
pwd

例子:

path.resolve('/foo/bar', './baz') 
// 输出结果为 
'/foo/bar/baz' 
path.resolve('/foo/bar', '/tmp/file/') 
// 输出结果为 
'/tmp/file' 

path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif') 
// 当前的工作路径是 /home/itbilu/node,则输出结果为 
'/home/itbilu/node/wwwroot/static_files/gif/image.gif'

3.对比

const path = require('path'); 
let myPath = path.join(__dirname,'/img/so'); //D:\myProgram\test\img\so 
let myPath2 = path.join(__dirname,'./img/so'); //D:\myProgram\test\img\so 
let myPath3 = path.resolve(__dirname,'/img/so'); // D:\img\so
let myPath4 = path.resolve(__dirname,'./img/so'); // D:\myProgram\test\img\so
console.log(__dirname); //D:\myProgram\test 
console.log(myPath); //D:\myProgram\test\img\so 
console.log(myPath2); //D:\myProgram\test\img\so 
console.log(myPath3); //D:\img\so<br> 
console.log(myPath4); //D:\myProgram\test\img\so

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值