Setting up process.env variables using EXPORT while running node with sudo

落爺英雄遲暮 提交于 2019-12-20 09:35:47

问题


I'm using node.js on EC2

I type

EXPORT PORT=80

in terminal, and i see that it correctly saves it when i type EXPORT

But when I run my node.js app with the following:

...
console.log(process.env);
...

PORT is not listed in the object when I'm running it with sudo:

sudo node app.js

How do I set PORT so that I can access it from the process.env object while running node with sudo?


回答1:


To set process.env variable use the following code:

sudo PORT=80 node server.js

Of course, you can set multiple process.env variables:

sudo PORT=80 HOST=localhost node server.js

Normally, EXPORT should work too. But sudo creates its own environments and then starts your program as root. So, you shall either add PORT to sudo's environment or force it to preserve your own environment.

To change sudo's environment you shall modify /root/.profile.

To force it to preserve your own environment use -E key:

sudo -E node app.js



回答2:


If you want to set this up permanently:

  1. Open up your bash profile vim ~/.bash_profile
  2. Add the environment variable to the file export PORT=80
  3. Open up the sudoers config file sudo visudo
  4. Add the following line to the file exactly as so Defaults env_keep +="PORT"

Now when you run sudo node app.js it should work as desired, with the port set to 80.



来源:https://stackoverflow.com/questions/14278024/setting-up-process-env-variables-using-export-while-running-node-with-sudo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!