Nodejs path.resolve 和 path.join

Nodejs的path模块,相比大家都不陌生。引入静态文件 各种path.join(_dirname,”XXX”),而path.join和reslove虽然概念很清晰,前者解析相对路径,后者解析绝对路径,但不上例子还是容易混淆。先看官网描述:

  1. The path.join() method joins all given path segments together using the platform specific separator as a delimiter, then normalizes the resulting path.

上述说明简单来说 path.join()就是连接路径,使用 系统的 分隔符

  1. The path.resolve() method resolves a sequence of paths or path segments into an absolute path.
    The given sequence of paths is processed from right to left, with each subsequent path prepended until an absolute path is constructed. For instance, given the sequence of path segments: /foo, /bar, baz, calling path.resolve(‘/foo’, ‘/bar’, ‘baz’) would return /bar/baz.

而path.resolve() 从右往左,解析成绝对路径,直到绝对路径被构建,其他没有使用的变量就不再使用。

来看几个例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const path = require('path');
console.log("__dirname",__dirname) //d:\Frontend\Nodejs\path 文件目录
var path1=path.join('app/libs/oauth', '/../ssl')
console.log('path1:',path1) //app\libs\ssl

var path2=path.resolve('/bar/bae', '/foo', 'test');
console.log('path2:',path2) //d:\foo\test(从右往左已经解析成了绝对路径!所有没有/bar/bea)

var path3= path.resolve('/foo/bar', '../tmp/file/');
console.log('path3:',path3) //d:\foo\tmp\file

var path4= path.resolve('/foo/bar', './tmp/file/'); //d:\foo\bar\tmp\file

var path3= path.resolve('foo/bar', './tmp/file/'); //d:\Frontend\Nodejs\path\foo\bar\tmp\file

var path5=path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif');
// if the current working directory is /home/myself/node,
// this returns '/home/myself/node/wwwroot/static_files/gif/image.gif'

最后来说一下在 非常常用的情况

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const path = require('path');

var path1=path.join(__dirname,'pubilc')
console.log("path1:",path1) //d:\Frontend\Nodejs\path\pubilc
//console.log(__dirname) //d:\Frontend\Nodejs\path

var path2=path.resolve(__dirname,'pubilc')
console.log('path2',path2) //d:\Frontend\Nodejs\path\pubilc
//常用的这种情况下 没区别


var path3=path.resolve(__dirname,'/pubilc')
console.log('path3',path3) //d:\pubilc
//根据上面例子 这样pubilc已经被解析成了绝对路径,所以这种写法不行。同理写成./pubilc也OK

值得注意的是

1
2
3
path.join(__dirname, '/src')
path.join(__dirname, './src')
path.join(__dirname, 'src')

这三种都是等价的,不要错误写成var path3=path.resolve(__dirname,'/pubilc') 被解析成绝对路径就好!

感觉写了片水文啊(捂脸

希望能对各位有帮助,感谢阅读!