官术网_书友最值得收藏!

Environment-based loading of middleware

While developing applications locally, we don't need to use components that enable gzip compression or database-backed sessions. Luckily, it's really simple to detect the current application environment.

In Express 3, there was an app.configure() function to detect the environment, but that was removed for newer versions. Nevertheless, all we have to do is pass the NODE_ENV environment variable (process.env.NODE_ENV) when starting the application; for example, see the following line of code:

NODE_ENV=production node env-middleware.js

Then, in our application, we can check for that variable and default to the development mode if it doesn't exist. Instead of writing the same if logic everywhere, we can create a tiny function to execute a callback if the environment matches the first parameter of the function (which is what app.configure() did). In case we want to set the environment in the code, we can create a closure that takes a single argument and returns the configuration function:

var configureByEnvironment = function(env) {
  if (!env) { env = process.env.NODE_ENV; }

  // default to development
  env = env || 'development';

  return function(env2, callback) {
    if (env === env2) { callback(); }
  };
};

This function acts as a setter for the environment variable and defaults to process.env.NODE_ENV if there is no argument sent. The next check detects whether the env variable is empty and defaults to development. The returned function resembles the app.configure() functionality and takes two parameters: the environment and the callback function that gets executed if the first parameter matches the current application mode.

A sample middleware setup can look like the following code:

var configure = configureByEnvironment();
var logger = require('morgan');
var compress = require('compression');
var responseTime = require('response-time');
var errorHandler = require('errorhandler');

configure('development', function() {
  app.use(logger('dev'));
  app.use(responseTime());
  app.use(express.static(__dirname + '/public'));
});

configure('production', function() {
  app.use(logger());
  // enable gzip compression for static resources in production
  app.use(compress());
  app.use(express.static(__dirname + '/public'));
});

As you might have noticed from the code, there are other things that change in different environments besides the middleware used, such as configuration options. In the production mode, it's better to use a verbose logger that provides more details of the request, while in development, it's enough to display the essential bits.

主站蜘蛛池模板: 夹江县| 图木舒克市| 资兴市| 沙洋县| 新乐市| 会泽县| 江华| 大丰市| 津市市| 安多县| 科技| 交城县| 盘锦市| 济南市| 玉环县| 浦北县| 澄迈县| 犍为县| 成武县| 鄂伦春自治旗| 从江县| 汨罗市| 南汇区| 冷水江市| 京山县| 曲沃县| 北海市| 双鸭山市| 岫岩| 临高县| 山丹县| 广丰县| 凤翔县| 卢湾区| 宁阳县| 千阳县| 新源县| 双鸭山市| 衡水市| 安化县| 年辖:市辖区|