Node.js 永远带有环境变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14618054/
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
Node.js forever with environment variable
提问by user1168427
The command I run on my server to start my node app is:
我在服务器上运行以启动节点应用程序的命令是:
sudo IS_PROD=1 node app.js
I have forever installed but can't seem to pass in the environment variable.
我已经永远安装了,但似乎无法传入环境变量。
sudo IS_PROD=1 forever node app.js
Doesn't seem to do the trick. I have tried several varieties of this. How do I either execute this command successfully or permanently set the environment variable?
似乎没有办法。我已经尝试了几种不同的方法。如何成功执行此命令或永久设置环境变量?
回答by Mattias
First of all you should skip the nodething in you command, it should not be there, you should not be able to execute that. foreverautomatically starts your script using nodejs. Instead you should do like this;
首先,您应该跳过node命令中的内容,它不应该在那里,您应该无法执行它。永远使用nodejs自动启动您的脚本。相反,你应该这样做;
sudo IS_PROD=1 forever app.js
Probably you, instead of starting your server in foreground, will want to start your server as a daemon. eg.
可能您不想在前台启动服务器,而是希望将服务器作为守护程序启动。例如。
sudo IS_PROD=1 forever start app.js
This will create a process in the background that will watch your node app and restart it when it exits. For more information see the readme.
这将在后台创建一个进程,该进程将监视您的节点应用程序并在它退出时重新启动它。有关更多信息,请参阅自述文件。
Both of these methods preserves the environment variables, just like when you are just using node.
这两种方法都保留了环境变量,就像您刚刚使用node.
回答by mak
app.js:
应用程序.js:
console.log(process.env.IS_PROD);
Using node(v0.8.21)
使用node(v0.8.21)
$ node app.js
undefined
$ IS_PROD=1 node app.js
1
$ sudo IS_PROD=1 node app.js
1
Using forever(v0.10.0)
使用forever(v0.10.0)
$ forever app.js
undefined
$ IS_PROD=1 forever app.js
1
$ sudo IS_PROD=1 forever app.js
1
文件:
process.env
An object containing the user environment. See environ(7).
进程.env
包含用户环境的对象。参见环境(7)。

