PORT=8080 was written in .env file sowhywe write const PORT = process.env.PORT || 8080 in server.js ,how is process.env.PORT value different from 8080

huangapple go评论54阅读模式
英文:

PORT=8080 was written in .env file sowhywe write const PORT = process.env.PORT || 8080 in server.js ,how is process.env.PORT value different from 8080

问题

PORT=8080 是写在 .env 文件中的,那么为什么我们在 server.js 中写 const PORT = process.env.PORT || 8080,process.env.PORT 的值与 8080 有什么不同?

在 server.js 中,我们可以只写 PORT = process.env.PORT 吗,而不是写 const PORT = process.env.PORT || 8080 吗?

英文:

PORT=8080 was written in .env file so why we write const PORT = process.env.PORT || 8080 in server.js ,how is process.env.PORT value different from 8080

can we only write PORT = process.env.PORT in server.js instead of const PORT = process.env.PORT || 8080 in server.js?

答案1

得分: 0

这是在JS中为变量提供默认值的经典方式。

|| 运算符接受两个参数。如果第一个参数被评估为“真值”,则运算符返回第一个参数。

let x = true || 'hello'    //true

如果第一个参数被评估为“假值”,则评估并返回第二个参数的结果。

let x = undefined || 'hello'   //hello

在你的情况下,同样的原理适用。如果 env.PORT 被设置,它将返回该值。如果没有设置,它将返回 8080

英文:

This is a classic way of providing a default value to a variable in JS.

The || operator takes two arguments. If the first argument is evaluated as "truthy", the operator returns the first argument.

let x = true || 'hello'    //true

If the first argument is evaluated "falsy", the second argument is evaluated and returned the results.

let x = undefined || 'hello'   //hello

The same principle is applied in your case. If the env.PORT is set, it will return the value. If not it will return 8080.

答案2

得分: -1

只返回翻译好的部分:

你可以只写 var PORT = process.env.PORT。|| 是用于部署目的和在本地环境中运行的。如果在 .env 文件中定义了任何端口,它将在该端口上运行,否则将在我们在 || 之后定义的端口上运行。

英文:

You can write only var PORT = process.env.PORT. The || we use for deployment purpose and to run in local env. If any port is defined in .env file it will run on that port otherwise it will run on port that we have defined after ||.

huangapple
  • 本文由 发表于 2023年7月20日 13:55:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76727026.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定