1. 程式人生 > 實用技巧 >nodejs.cn-Node.js-入門教程:Node.js 開發環境與生產環境的區別

nodejs.cn-Node.js-入門教程:Node.js 開發環境與生產環境的區別

ylbtech-nodejs.cn-Node.js-入門教程:Node.js 開發環境與生產環境的區別

1.返回頂部
1、

Node.js 開發環境與生產環境的區別

You can have different configurations for production and development environments.

Node.js assumes it's always running in a development environment. You can signal Node.js that you are running in production by setting theNODE_ENV=production

environment variable.

This is usually done by executing the command

export NODE_ENV=production

in the shell, but it's better to put it in your shell configuration file (e.g..bash_profilewith the Bash shell) because otherwise the setting does not persist in case of a system restart.

You can also apply the environment variable by prepending it to your application initialization command:

NODE_ENV=production node app.js

This environment variable is a convention that is widely used in external libraries as well.

Setting the environment toproductiongenerally ensures that

  • 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 ifNODE_ENV

is not set toproduction. 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())
})
2、
2.返回頂部
3.返回頂部
4.返回頂部
5.返回頂部
1、 http://nodejs.cn/learn/nodejs-the-difference-between-development-and-production 2、
6.返回頂部
作者:ylbtech
出處:http://ylbtech.cnblogs.com/
本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段宣告,且在文章頁面明顯位置給出原文連線,否則保留追究法律責任的權利。