Difference between path.normalize and path.resolve in Node.js

前端 未结 2 1829
予麋鹿
予麋鹿 2021-01-29 23:39

What is the difference (if any) between path.normalize(your_path) and path.resolve(your_path)?

I know path.resolve(...) can accept

2条回答
  •  一生所求
    2021-01-30 00:23

    path.normalize gets rid of the extra ., .., etc. in the path. path.resolve resolves a path into an absolute path. Example (my current working directory was /Users/mtilley/src/testing):

    > path.normalize('../../src/../src/node')
    '../../src/node'
    > path.resolve('../../src/../src/node')
    '/Users/mtilley/src/node'
    

    In other words, path.normalize is "What is the shortest path I can take that will take me to the same place as the input", while path.resolve is "What is my destination if I take this path."

    Note however that path.normalize() is much more context-independent than path.resolve(). Had path.normalize() been context-dependent (i.e. if it had taken into consideration the current working directory), the result in the example above would've been ../node, because that's the shortest path one could take from /Users/mtilley/src/testing to /Users/mtilley/src/node.

    Ironically, this means that path.resolve() produces a relative path in absolute terms (you could execute it anywhere, and it would produce the same result), whereas path.normalize() produces an absolute path in relative terms (you must execute it in the path relative to which you want to calculate the absolute result).

提交回复
热议问题