返回值
- path.resolve 返回值是符合路径规范的字符串,无参数默认优先返回表示the current working directory的绝对路径的字符串,如果process.cwd() fails,则返回表示the current working directory的字符串
"."
- path.join 返回值是符合路径规范的字符串,无参数默认返回表示the current working directory的字符串
"."
代码演示:https://repl.it/@panhezeng/pathresolve-and-pathjoin-return-value
在特定参数下,path.resolve 和 path.join的返回值是一样的,比如webpack官方文档中出现的示例代码:
path.resolve(__dirname, "dist");
下面代码的返回值和上面的返回值是一样的。
path.join(__dirname, "dist");
path.resolve() 无参数默认返回值 和 __dirname 的区别
If no path
segments are passed, path.resolve()
will return the absolute path of the current working directory.
当调用 path.resolve 时没有传参数,或者传的参数,都不符合绝对路径规范时,内部是把 process.cwd() 的返回值加在处理完参数后得到的返回值的前面,所以 path.resolve() 无参数默认返回值 和 __dirname 的区别,也就是 process.cwd() 和 __dirname 的区别。
The process.cwd()
method returns the current working directory of the Node.js process.
__dirname : The directory name of the current module. This is the same as the path.dirname()
of the __filename
.
__filename : The file name of the current module. This is the current module file’s absolute path with symlinks resolved.
代码演示:https://repl.it/@panhezeng/pathresolve-and-dirname
遍历字符串参数
path.resolve是从右到左遍历字符串参数,可能会中途退出遍历。
for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--){}
path.join是从左到右遍历字符串参数,不会中途退出遍历。
for (let i = 0; i < args.length; ++i) { }
源码
我把node源码中path.resolve和path.join的部分提取出来,并加上了详细注释,仅提取了posix部分,并且注释掉了validateString方法,path.resolve和path.join的核心是path.normalizeString
源码注释:https://repl.it/@panhezeng/pathresolve-and-pathjoin-source-code
开发中遇到读取文件,写入文件,创建文件夹等需求,就要用到 path.resolve 或path.join 。虽然在特定条件下,path.resolve 和 path.join 可以获得同样的结果,也就是说它们可以相互替代,但是当明确需要获得文件夹或文件的绝对路径时,建议使用path.resolve,并且使用 __dirname 作为第一个参数,否则如果 process.cwd() fails ,则可能出现非预期的结果。
repl.it 可能需要代理才能访问,我已经向官方反馈增加中国CDN。
本文遵循署名-非商业性使用共享协议,转载请注明。