Skip to content

path.join 和 path.resolve 有什么区别?

拼接绝对路径时表现相同

js
  function resolve(...args: Array<string>) {
    return path.resolve(...args)
  }
  function join(...args: Array<string>) {
    return path.join(...args)
  }
  const path1 = 'C:/Users/lukecheng/Desktop/code/my-test-build-project/test'

  console.log(resolve(path1))
  console.log(join(path1))
  // C:/Users/lukecheng/Desktop/code/my-test-build-project/test
  resolve(path1) === join(path1) // true

path.resolve 总是返回绝对路径

如果路径是以斜杠 / 开头或系统盘开头,那么 path.join 返回的路径还是以斜杠 / 开头,而 path.resolve 会以 <系统盘符:\\> 开头。

js
  function resolve(...args: Array<string>) {
    return path.resolve(...args)
  }
  function join(...args: Array<string>) {
    return path.join(...args)
  }

  const path2 = '/my-test-build-project/test'

  console.log(resolve(path2)) // C:\my-test-build-project\test
  console.log(join(path2)) // \my-test-build-project\test

但如果是以 ./ 开头,那么 path.join 将会把 ./ 去掉,而 path.resolve 则返回一个绝对路径。

js
  function resolve(...args: Array<string>) {
    return path.resolve(...args)
  }
  function join(...args: Array<string>) {
    return path.join(...args)
  }
  const path1 = './my-test-build-project/test'

  // C:\Users\lukecheng\Desktop\code\build-scripts\my-test-build-project\test
  console.log(resolve(path1))
  // my-test-build-project\test
  console.log(join(path1))

总结

path.resolve 总是返回绝对路径,而 path.join 则不一定。

Released under the MIT License.