path.join vs path.resolve with __dirname

前端 未结 3 1840
难免孤独
难免孤独 2020-12-04 08:11

Is there a difference when using both path.join and path.resolve with __dirname for resolving absolute path in Node.js?

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-04 08:30

    Yes there is a difference between the functions but the way you are using them in this case will result in the same outcome.

    path.join returns a normalized path by merging two paths together. It can return an absolute path, but it doesn't necessarily always do so.

    For instance:

    path.join('app/libs/oauth', '/../ssl')
    

    resolves to app/libs/ssl

    path.resolve, on the other hand, will resolve to an absolute path.

    For instance, when you run:

    path.resolve('bar', '/foo');
    

    The path returned will be /foo since that is the first absolute path that can be constructed.

    However, if you run:

    path.resolve('/bar/bae', '/foo', 'test');
    

    The path returned will be /foo/test again because that is the first absolute path that can be formed from right to left.

    If you don't provide a path that specifies the root directory then the paths given to the resolve function are appended to the current working directory. So if your working directory was /home/mark/project/:

    path.resolve('test', 'directory', '../back');
    

    resolves to

    /home/mark/project/test/back

    Using __dirname is the absolute path to the directory containing the source file. When you use path.resolve or path.join they will return the same result if you give the same path following __dirname. In such cases it's really just a matter of preference.

提交回复
热议问题