无法在我的Node.js应用中读取环境变量 [英] Can't read my environment variable in my Node.js app

查看:306
本文介绍了无法在我的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'

这篇关于无法在我的Node.js应用中读取环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆