2 Configuring Express and Our Application - OpenTechConsult/shoutbox GitHub Wiki
Our application's requirements will depend on the environment in which it's running. For example we may need verbose logging when our application is in development, but leaner set of logs and gzip compression when it's in production.
In addition to environment-specific functionality configuration, we may want some application-level settings so Express knows what template engine we are using and where it can find the templates. Express let us also define custom configuration key/value pairs
To set environment variable in UNIX systems we can use this command:
$ NODE_ENV=production node app
In Windows we can use the following command:set NODE_ENV=production
node app
These environment variables will be accessible in our application via theprocess.env
object.
Express has a minimal environment-driven configuration system, consisting of several methods, all driven by the NODE_ENV environment variable:
- app.set()
- app.get()
- app.enable()
- app.disable()
- app.enabled()
- app.disabled()
We'll learn how to use the configuration system to customize the way Express behaves and how to use this system for our own purposes throughout development?
Let's take a closer look at what environment-based configuration means. Although the NODE_ENV environment variable originated in Express many other Node frameworks have adopted it as a means to notify the Node application which environment it's operating within, defaulting to development
The app.configure
methods accepts optional string representing the environment, and a function. When environment matches the string passed, the callback is immediately invoked; when only a function is given, it's invoked for all environments. These environment names are arbitrary. For example we may have development, stage, test, and production
if(app.get('env') === 'development') {
app.use(express.errorHandler());
}
Express uses this configuration system internally, allowing us to customize how Express behaves. But it's also available for our own use.
Express provide boolean variants for app.set()
and app.get()
For example app.enable(setting) <===> app.set(setting, true) app.enabled(setting) ==> to check whether the value was enabled.
A useful setting for developing API with Express is the json spaces option. If added to our app.js file, our JSON will be printed in a more readable format.
app.set('json spaces' 2);
Next step is to look at how to render views in express.