Node.js,开发和生产之间的区别

¥Node.js, the difference between development and production

Node.js 中的开发和生产没有区别,即,你无需应用任何特定设置即可使 Node.js 在生产配置中工作。但是,npm 注册表中的一些库会识别使用 NODE_ENV 变量并将其默认为 development 设置。始终在设置了 NODE_ENV=production 的情况下运行 Node.js。

¥There is no difference between development and production in Node.js, i.e., there are no specific settings you need to apply to make Node.js work in a production configuration. However, a few libraries in the npm registry recognize using the NODE_ENV variable and default it to a development setting. Always run your Node.js with the NODE_ENV=production set.

配置应用的一种流行方法是使用 十二因素方法论

¥A popular way of configuring your application is by using the twelve factor methodology.

为什么 NODE_ENV 被视为反模式?

¥Why is NODE_ENV considered an antipattern?

环境是一个数字平台或系统,工程师可以在其中构建、测试、部署和管理软件产品。通常,我们的应用运行的环境有四个阶段或类型:

¥An environment is a digital platform or a system where engineers can build, test, deploy, and manage software products. Conventionally, there are four stages or types of environments where our application is run:

  • 开发

    ¥Development

  • 测试

    ¥Testing

  • 准备

    ¥Staging

  • 生产

    ¥Production

NODE_ENV 的根本问题源于开发者将优化和软件行为与其软件运行的环境相结合。结果是如下代码:

¥The fundamental problem of NODE_ENV stems from developers combining optimizations and software behavior with the environment their software is running on. The result is code like the following:

if (process.env.NODE_ENV === 'development') {
  // ...
}

if (process.env.NODE_ENV === 'production') {
  // ...
}

if (['production', 'staging'].includes(process.env.NODE_ENV)) {
  // ...
}

虽然这看起来无害,但它使生产和登台环境不同,从而使可靠的测试变得不可能。例如,当 NODE_ENV 设置为 development 时,测试以及产品的功能可能会通过,但当将 NODE_ENV 设置为 production 时会失败。因此,将 NODE_ENV 设置为 production 以外的任何值都被视为反模式。

¥While this might look harmless, it makes the production and staging environments different, thus making reliable testing impossible. For example a test and thus a functionality of your product could pass when NODE_ENV is set to development but fail when setting NODE_ENV to production. Therefore, setting NODE_ENV to anything but production is considered an antipattern.