Node.js 开发环境与生产环境的区别

可以为生产环境和开发环境使用不同的配置。

Node.js 假定其始终运行在开发环境中。 可以通过设置 NODE_ENV=production 环境变量来向 Node.js 发出正在生产环境中运行的信号。

通常通过在 shell 中执行以下命令来完成:

export NODE_ENV=production

但最好将其放在的 shell 配置文件中(例如,使用 Bash shell 的 .bash_profile),否则当系统重启时,该设置不会被保留。

也可以通过将环境变量放在应用程序的初始化命令之前来应用它:

NODE_ENV=production node app.js

此环境变量是一个约定,在外部库中也广泛使用。

设置环境为 production 通常可以确保:

  • logging is kept to a minimum, essential level
  • more caching levels take place to optimize performance

For example Pug, the templating library used by Express, compiles in debug mode if NODE_ENV is not set to production. Express views are compiled in every request in development mode, while in production they are cached. There are many more examples.

You can use conditional statements to execute code in different environments:

if (process.env.NODE_ENV === "development") {
  //...
}
if (process.env.NODE_ENV === "production") {
  //...
}
if(['production', 'staging'].indexOf(process.env.NODE_ENV) >= 0) {
  //...
})

For example, in an Express app, you can use this to set different error handlers per environment:

if (process.env.NODE_ENV === "development") {
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }))
})

if (process.env.NODE_ENV === "production") {
  app.use(express.errorHandler())
})