Node.js, express, and using development versus production in app.configure

后端 未结 5 1472
孤城傲影
孤城傲影 2020-12-07 14:44

What is the easiest method to let express know what environment I am in? E.g. I want do do the below to make a connection to redis depending on what env I am in. Can this

5条回答
  •  囚心锁ツ
    2020-12-07 15:48

    Your approach is ok, but you can make something more generic, like storing the config data for Redis in a file or passing the host and port like arguments:

    node app.js REDIS_HOST REDIS_PORT

    Then in your app you can grab them using process.argv:

    app.configure('development', function(){
      app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
      var r = require("redis").createClient(process.argv[2], process.argv[3]);
    });
    app.configure('production', function(){
      app.use(express.errorHandler());
      var r = require("redis").createClient(process.argv[2], process.argv[3], { detect_buffers: true });
    });
    

    Update:

    Express will know in what environment you're in by looking at the NODE_ENV variable (process.env.NODE_ENV): https://github.com/visionmedia/express/blob/master/lib/application.js#L55

    You can set that variable when starting the app like so: NODE_ENV=production node app.js (recommended), setting process.env.NODE_ENV manually in your node app before the Express code or putting that env var in ~/.profile like Ricardo said.

提交回复
热议问题