Node.js 中 path 正规化与 path 解析的区别

path.normalize(your_path)path.resolve(your_path)有什么不同(如果有的话) ?

我知道 path.resolve(...)可以接受多个参数,但是只有一个参数的行为是否与调用 path.normalize()相同?

编辑: 如果它们应该以相同的方式运行,我不理解当你只需要简单地将路径传递到 path.resolve(...)或者,也许,它是为了文档的目的而暴露 path.normalize(...)函数的目的。例如,他们在 path.resolve(...)的文档中说:

产生的路径被标准化了。

暴露 path.normalize(...)能更容易解释“标准化”是什么意思? 我不知道。

55693 次浏览

From the docs:

Another way to think of resolve is as a sequence of cd commands in a shell.

Links to path.resolve and path.normalize in the documentation. I mostly don't want to just provide links in an answer but the Node.js docs are very decent.

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).