简体   繁体   English

什么是 NODE_ENV 以及如何在 Express 中使用它?

[英]What is NODE_ENV and how to use it in Express?

This is my the app, I'm currently running on production.这是我的应用程序,我目前正在生产中运行。

var app = express();
app.set('views',settings.c.WEB_PATH + '/public/templates');
app.set('view engine','ejs');
app.configure(function(){
    app.use(express.favicon());
    app.use(express.static(settings.c.WEB_PATH + '/public'));
    app.use(express.bodyParser());
    app.use(express.cookieParser());
    app.use(express.methodOverride());
    app.use(express.session({
            cookie:{ domain:"."+settings.c.SITE_DOMAIN, maxAge:1440009999},
            secret:'hamster',
            store: r_store,
            }));
    app.use(useragent.express());
    app.use(flash());
    app.use(passport.initialize());
    app.use(passport.session());
});

However, I came to know about NODE_ENV and want to use it.但是,我开始了解NODE_ENV并想使用它。 How can I do this?我怎样才能做到这一点?

NODE_ENV is an environment variable made popular by the express web server framework. NODE_ENV是由express Web 服务器框架流行的环境变量 When a node application is run, it can check the value of the environment variable and do different things based on the value.当一个节点应用程序运行时,它可以检查环境变量的值并根据该值做不同的事情。 NODE_ENV specifically is used (by convention) to state whether a particular environment is a production or a development environment. NODE_ENV专门用于(按照惯例)来说明特定环境是生产环境还是开发环境。 A common use-case is running additional debugging or logging code if running in a development environment.如果在开发环境中运行,一个常见的用例是运行额外的调试或日志记录代码。

Accessing NODE_ENV访问 NODE_ENV

You can use the following code to access the environment variable yourself so that you can perform your own checks and logic:您可以使用以下代码自己访问环境变量,以便您可以执行自己的检查和逻辑:

var environment = process.env.NODE_ENV

Assume production if you don't recognise the value:如果您不承认价值,则假设生产:

var isDevelopment = environment === 'development'

if (isDevelopment) {
  setUpMoreVerboseLogging()
}

You can alternatively using express' app.get('env') function, but note that this is NOT RECOMMENDED as it defaults to "development" , which may result in development code being accidentally run in a production environment - it's much safer if your app throws an error if this important value is not set (or if preferred, defaults to production logic as above).您也可以使用 express' app.get('env')函数,但请注意,不推荐这样做,因为它默认为"development" ,这可能会导致开发代码在生产环境中意外运行 - 如果您使用它会更安全如果未设置此重要值(或者如果首选,默认为上述生产逻辑),应用程序将引发错误。

Be aware that if you haven't explicitly set NODE_ENV for your environment, it will be undefined if you access it from process.env , there is no default.请注意,如果您没有为您的环境明确设置NODE_ENV ,那么如果您从process.env访问它,它将是undefined ,没有默认值。

Setting NODE_ENV设置 NODE_ENV

How to actually set the environment variable varies from operating system to operating system, and also depends on your user setup.如何实际设置环境变量因操作系统而异,还取决于您的用户设置。

If you want to set the environment variable as a one-off, you can do so from the command line:如果要将环境变量设置为一次性的,可以从命令行执行此操作:

  • linux & mac : export NODE_ENV=production linux & mac : export NODE_ENV=production
  • windows : $env:NODE_ENV = 'production'窗口$env:NODE_ENV = 'production'

In the long term, you should persist this so that it isn't unset if you reboot - rather than list all the possible methods to do this, I'll let you search how to do that yourself!从长远来看,您应该坚持这一点,以便在您重新启动时不会取消设置 - 而不是列出所有可能的方法来做到这一点,我会让您自己搜索如何做到这一点!

Convention has dictated that there are two 'main' values you should use for NODE_ENV , either production or development , all lowercase.约定规定,您应该为NODE_ENV使用两个“主要”值, productiondevelopment ,全部小写。 There's nothing to stop you from using other values, ( test , for example, if you wish to use some different logic when running automated tests), but be aware that if you are using third-party modules, they may explicitly compare with 'production' or 'development' to determine what to do, so there may be side effects that aren't immediately obvious.没有什么可以阻止您使用其他值(例如, test ,如果您希望在运行自动化测试时使用一些不同的逻辑),但请注意,如果您使用第三方模块,它们可能会显式地与'production'进行比较'production''development'来决定要做什么,所以可能会有不立即明显的副作用。

Finally, note that it's a really bad idea to try to set NODE_ENV from within a node application itself - if you do, it will only be applied to the process from which it was set , so things probably won't work like you'd expect them to.最后,请注意,这是一个非常糟糕的主意,试图设置NODE_ENV从节点应用程序本身-如果你这样做,这将只适用于从它被设置的过程中,这样的事情可能会不喜欢你的工作会期待他们。 Don't do it - you'll regret it.不要这样做 - 你会后悔的。

NODE_ENV is an environmental variable that stands for node environment in express server. NODE_ENV是一个环境变量,代表 express 服务器中的节点环境

It's how we set and detect which environment we are in.这就是我们如何设置和检测我们所处的环境。

It's very common using production and development .使用productiondevelopment非常普遍。

Set:放:

export NODE_ENV=production

Get:得到:

You can get it using app.get('env')您可以使用app.get('env')获取它

I assume the original question included how does Express use this environment variable.我假设最初的问题包括 Express 如何使用这个环境变量。

Express uses NODE_ENV to alter its own default behavior. Express 使用 NODE_ENV 来改变它自己的默认行为。 For example, in development mode, the default error handler will send back a stacktrace to the browser.例如,在开发模式下,默认错误处理程序会将堆栈跟踪发送回浏览器。 In production mode, the response is simply Internal Server Error , to avoid leaking implementation details to the world.在生产模式下,响应只是Internal Server Error ,以避免将实现细节泄露给全世界。

Typically, you'd use the NODE_ENV variable to take special actions when you develop, test and debug your code.通常,您会在开发、测试和调试代码时使用NODE_ENV变量来执行特殊操作。 For example to produce detailed logging and debug output which you don't want in production.例如,生成您不希望在生产中使用的详细日志记录和调试输出。 Express itself behaves differently depending on whether NODE_ENV is set to production or not. Express 本身的行为取决于NODE_ENV是否设置为production You can see this if you put these lines in an Express app, and then make a HTTP GET request to /error :如果将这些行放在 Express 应用程序中,然后向/error发出 HTTP GET 请求,则可以看到这一点:

app.get('/error', function(req, res) {
  if ('production' !== app.get('env')) {
    console.log("Forcing an error!");
  }
  throw new Error('TestError');
});

app.use(function (req, res, next) {
  res.status(501).send("Error!")
})

Note that the latter app.use() must be last, after all other method handlers!请注意,在所有其他方法处理程序之后,后面的app.use()必须是最后一个!

If you set NODE_ENV to production before you start your server, and then send a GET /error request to it, you should not see the text Forcing an error!如果在启动服务器之前将NODE_ENV设置为production ,然后向其发送GET /error请求,则不应看到文本Forcing an error! in the console, and the response should not contain a stack trace in the HTML body (which origins from Express).在控制台中,响应不应在 HTML 正文(源自 Express)中包含堆栈跟踪。 If, instead, you set NODE_ENV to something else before starting your server, the opposite should happen.相反,如果您在启动服务器之前将NODE_ENV设置为其他内容,则会发生相反的情况。

In Linux, set the environment variable NODE_ENV like this:在 Linux 中,像这样设置环境变量 NODE_ENV:

export NODE_ENV=' value '导出 NODE_ENV=''

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM