如何更改 node.js 中 process.env.PORT 的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13333221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change value of process.env.PORT in node.js?
提问by Dennis
I'd like to change the value of process.env.PORT, how can I do this?
我想更改 的值process.env.PORT,我该怎么做?
I'm running Ubuntu 12.04.
我正在运行 Ubuntu 12.04。
回答by JohnnyHK
For just one run (from the unix shell prompt):
仅运行一次(来自 unix shell 提示):
$ PORT=1234 node app.js
More permanently:
更永久:
$ export PORT=1234
$ node app.js
In Windows:
set PORT=1234
In Windows PowerShell:
在 Windows PowerShell 中:
$env:PORT = 1234
回答by v2p
You can use cross platform solution https://www.npmjs.com/package/cross-env
您可以使用跨平台解决方案https://www.npmjs.com/package/cross-env
$ cross-env PORT=1234
回答by Vikash Kumar
use the below command to set the port number in node process while running node JS programme:
在运行 node JS 程序时,使用以下命令设置 node 进程中的端口号:
set PORT =3000 && node file_name.js
The set port can be accessed in the code as
设置端口可以在代码中访问为
process.env.PORT
回答by Kyle Chadha
EDIT:Per @sshow's comment, if you're trying to run your node app on port 80, the below is not the best way to do it. Here's a better answer: How do I run Node.js on port 80?
编辑:根据@sshow 的评论,如果您尝试在端口 80 上运行您的节点应用程序,则以下方法不是最好的方法。这是一个更好的答案:如何在端口 80 上运行 Node.js?
Original Answer:
原答案:
If you want to do this to run on port 80 (or want to set the env variable more permanently),
如果您想这样做以在端口 80 上运行(或想更永久地设置 env 变量),
- Open up your bash profile
vim ~/.bash_profile - Add the environment variable to the file
export PORT=80 - Open up the sudoers config file
sudo visudo - Add the following line to the file exactly as so
Defaults env_keep +="PORT"
- 打开您的 bash 个人资料
vim ~/.bash_profile - 将环境变量添加到文件中
export PORT=80 - 打开 sudoers 配置文件
sudo visudo - 将以下行完全如此添加到文件中
Defaults env_keep +="PORT"
Now when you run sudo node app.jsit should work as desired.
现在,当您运行时,sudo node app.js它应该可以正常工作。

