Node.js,开发环境与生产环境的区别
🌐 Node.js, the difference between development and production
在 Node.js 中,开发环境和生产环境没有区别,也就是说,你不需要应用任何特定设置来让 Node.js 在生产配置中运行。然而,npm 注册表中的一些库会识别 NODE_ENV 变量,并将其默认设置为 development。始终在运行 Node.js 时设置 NODE_ENV=production。
配置应用的一种流行方式是使用 twelve factor methodology。
🌐 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:
- 发展
- 测试
- 分期
- 生产
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 (.. === 'development') {
// ...
}
if (.. === 'production') {
// ...
}
if (['production', 'staging'].(..)) {
// ...
}
虽然这看起来无害,但它会使生产环境和暂存环境不同,从而使可靠的测试变得不可能。例如,当 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.