How do you detect the environment in an express.js app?

后端 未结 6 992
谎友^
谎友^ 2020-12-23 01:48

How do you detect what environment an expressJS app is running in? (development, test, production?). There\'s nothing in process.env indicating an environment..

相关标签:
6条回答
  • 2020-12-23 02:22

    There are a lot of useful recommendations in other answers. I'm generally doing it like this:

    const environment = process.env.NODE_ENV || 'development';
    

    The good thing is that such approach is not specific to Express per se, but actually is an accepted practice in wider Node.js ecosystem.

    Also, I've implemented a reusable module, which allows to automatically detect environment by analyzing both CLI arguments and NODE_ENV variable. This could be useful on your development machine, because you can easily change environment by passing a CLI argument to you Node.js program like this: $ node app.js --prod.

    Please see more details and use cases on the detect-environment's page.

    0 讨论(0)
  • 2020-12-23 02:23

    You can either check the environment by checking the app.settings.env (this will work in Express), or you can do it in a more direct way by checking process.env.NODE_ENV (the environment is the one found in that variable or 'development' by default < this also works in other libraries such as Socket.IO etc).

    0 讨论(0)
  • 2020-12-23 02:23

    app.get('env') would also return the environment.

    if ( app.get('env') === 'development' ) {
        app.use(express.errorHandler());
    }
    
    0 讨论(0)
  • 2020-12-23 02:24

    I'd like to address a straightforward way to passing NODE_ENV variables to your node script in order to access them in process.env

      "scripts": {
        "start": "./node_modules/.bin/cross-env NODE_ENV=development ./node_modules/.bin/nodemon server.js",
        "debug": "./node_modules/.bin/cross-env NODE_ENV=development ./node_modules/.bin/nodemon --debug server.js",
        "test": "./node_modules/.bin/cross-env NODE_ENV=test ./node_modules/.bin/babel-tape-runner test/test-*.js"
      },
    

    can be used as

    if ( app.get('env') === 'development' ) {
        app.use(express.errorHandler());
    }
    
    0 讨论(0)
  • 2020-12-23 02:30

    The can detect which environment you are in by inspecting app.settings.env.

    0 讨论(0)
  • 2020-12-23 02:44

    cannot access the nodejs server. can detect node env from express using app.setting.env

    1. var app = express();
    2. app.setting.env render to the template engine.
    3. check from the browser.
    0 讨论(0)
提交回复
热议问题