无法在我的Node.js应用中读取环境变量
我在Ubuntu 12.04上,我只是在学习环境变量.我试图从我的应用程序中读取一个自定义变量,但它始终显示为undefined
.这是我的测试应用程序的代码:
I am on Ubuntu 12.04 and I'm just learning about environment variables. I am trying to read a custom variable from within my application but it always shows up as undefined
. Here is the code of my test app:
// app.js
console.log('Value: ' + process.env.NODE_ENV);
如果我运行以下命令,您将看到该变量具有一个值:
If I run the following commands you will see that the variable has a value:
$ NODE_ENV=production
$ echo $NODE_ENV
production
我可以整天echo $NODE_ENV
,它将继续显示生产",但是当我在Node应用程序中执行process.env.NODE_ENV
时,它始终显示未定义".
I can echo $NODE_ENV
all day and it will continue to show me "production", but when I do process.env.NODE_ENV
in my Node application it always displays "undefined".
$ node app.js
Value: undefined
但是,这是一个奇怪的部分,如果我显示另一个我知道已经存在的环境变量,例如process.env.PATH
,那么它将起作用.
Here is the odd part though, if I display another environment variable that I know already exists, say process.env.PATH
, then it works.
$ node app.js
Value: /usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
另一个怪癖是,尽管echo $NODE_ENV
向我显示了正确的值,但命令printenv list
似乎没有包含我的自定义变量NODE_ENV
. printenv NODE_ENV
也没有显示任何内容,但是printenv PATH
显示了正确的值,就像我在节点应用程序中访问PATH
时一样.
Another quirk is that the command printenv list
doesn't appear to contain my custom variable NODE_ENV
despite the fact that echo $NODE_ENV
shows me the correct value. printenv NODE_ENV
shows nothing as well, but printenv PATH
shows the proper value just as it did when I accessed PATH
in my node application.
您需要export
shell变量,以使它们可用于您在shell中执行的进程.
You need to export
shell variables in order to make them available to processes you execute in your shell.
比较此命令的输出:
FOO=bar; bash -c 'echo $FOO'
具有以下输出:
export FOO=bar; bash -c 'echo $FOO'