Is there some difference between the following invocations?

path.join(__dirname, 'app')

vs.

path.resolve(__dirname, 'app')

Which one should be preferred?

推荐答案

The two functions deal with segments starting with / in very different ways; join will just concatenate it with the previous argument, however resolve will treat this as the root directory, and ignore all previous paths - think of it as the result of executing cd with each argument:

path.join('/a', '/b') // Outputs '/a/b'

path.resolve('/a', '/b') // Outputs '/b'

Another thing to note is that path.resolve will always result in an absolute URL, and will use your working directory as a base to resolve this path. But as __dirname is an absolute path anyway this doesn't matter in your case.

As for which one you should use, the answer is: it depends on how you want segments starting in / to behave - should they be simply joined or should they act as the new root?

If the other arguments are hard coded it really doesn't matter, in which case you should probably consider (a) how this line might change in future and (b) how consistent is it with other places in the code.

Node.js相关问答推荐

如何处理EPIPE时,使用axios并期待413响应?

在我的Next.js应用程序中没有正确设置Process.env.NODE_ENV

DocuSign:调用createEntaine时,RequestJWTApplicationToken返回401 AUTHORIZATION_INVALID_TOKEN

Mongoose抱怨说,整数是数字,而不是整数

如何使用多个参数完成

如何在医学中按patientId查找一个并同时插入多个数据

向url传递多个参数

为什么 Cors 在 NodeJS 中不起作用

如何模拟 mysql2 `getConnection`

密码加密的最佳实践是什么?

TypeError:在使用 Jest、Supertest、Express、Typescript 进行测试时无法读取未定义的属性(读取listen)

使用正则表达式查找文档,但输入是数组

从数据库读取数据并将其作为可下载的 zip 文件发送

如何限制 cron 表单将消息推送到 RabbitMQ?

socket.io 发出回调合适吗?

如何让should.be.false语法通过 jslint?

向 Stripe 提交付款请求时出现没有此类令牌错误

node.js(ES6 / Babel)中 import X 和 import * as X 的区别?

expressjs app.VERB 调用中的 next() 和 next('route') 有什么区别?

FireStore 如果不存在则创建一个文档