Setting different config files in Node.js

External config files
Node.JS logo

When it comes to configuration options it is always desirable to avoid hardcoding config values in our code. Even more, if we are using different config values in development and production environments it is necessary an easy way to switch from one to another. This also becomes useful when your code is public but you want to hide some config files. In Node.js there is more than one way to do this.

Using config module

Easy to install, easy to configure, easy to use. The module you need is named config and you can have it just doing npm install config or adding config in the dependencies section of your packages.json file:

{
  "name": "world-domination-project",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app"
  },
  "dependencies": {
    "express": "~4.2.0",
     "config": "~0.4.36",
     "mongoose": "*",
    "debug": "~0.7.4"
  }
}

The project is hosted on github, and just taking a look to the README you can set everything up.

Creating config files

First of all, in your project root you must create a folder called config with a mkdir config o whatever. If you love troubles and you don't like to be said what and where do you have to create folders, you'll have to set the $NODE_CONFIG_DIR variable.

If you want more details just read more about configuration files options. You can pick between many different flavors of config syntax: json, yaml, cofeescript, js,... What I am showing here is quite simple: a default config and a production configuration in json format.

config/default.json

default.json is the first file that config module tries to get. So this is fine for development, and this is how it looks like:

/**
 * default config file
 */
{
    "www" : {
        "port" : 3000
        },
    "db": {
        "host": "localhost",
        "port": "27017",
        "dbname": "blog",
        "username" : "",
        "password" : ""
        },
    "debug": {
        "level": 0
    }
}
config/production.json

Here comes the production config, with the same keys but with different values. As you may expect, ports, hosts, passwords, are different.

{
    "www" : {
        "port" : 80
    },
    "db": {
        "host": "imsokweliuse.mongolabs.net",
        "port": "27017",
        "dbname": "blog",
        "username" : "snowden",
        "password" : "changeme"
    },
    "debug": {
        "level": 1
    }
}
Applying config file

Very easily, just require config module and you are ready to go. The json file is loaded and everything is handled in a variable. If you want to apply the production.json file, you have to set NODE_ENV environment variable to production, this way: export $NODE_ENV=production. That is something that maybe in your production server is already set. As for the code, behold the config module working:

/**
* app.js - pello altadill
* @greetz to any
*/
...
var express = require('express');
var mongoose = require('mongoose');
var mongooseTypes = require("mongoose-types");
var config = require('config');

mongooseTypes.loadTypes(mongoose);

console.log("Show conf:" + config.www.port);

mongoose.connect('mongodb://'+config.db.username+':'+config.db.password+'@'+config.db.host+':'+config.db.port+'/'+config.db.dbname);
var app = express();
...

Yeah I know, maybe instead of splitting all the database config we should just set one url containing everything. Do it your way.

by Pello Altadill 2 Days ago - 45 hits

Enabling basic authentication for MongoDB databases

MongoDB is extremely easy to install and run. If you are not able to make it work maybe you could feel more confortable using Access or even excel. Well, sorry for that. This short article is but a quick and dirty guide to enable basic authentication in mongodb, and how to create one database with its own user (not a superadmin) with just read/write permissions. If you run mongo...

by Pello Altadill 4 Days ago - 75 hits

More »

Python language basics

Python in 21 minutes (or so) For a developer is not enough to know one programming language, it is often said that is good to know many of them. After all the language is but a mere tool to build programs. Python has been around for many years and one of my pending task was to take a look at it. Some friends (@Eugenia4v,@Claw_Shadow,@D00m3dr4v3n) are always tellin...

by Pello Altadill 07/12/2014 23:51:05 - 177 hits

More »

A night out with Jasmine

A night out with Jasmine Unit testing is much more than a tool for ensuring that a program behaves as expected. Nowadays it's the key for new development techniques such as TDD and BDD in which you begin writing tests before the required code. It's all about requirements and behaviour; developers must focus on understanding the requirements instead of thinking about the way they implement the code. In the event that you've forgotten the fundamental benefits of unit testing here you have a quick...

by Pello Altadill 04/23/2014 00:37:18 - 1538 hits

More »

Arkapong

This a classic pong-like game that takes some ideas from Arkanoid. Basically two paddles try to hit the ball until one of them fails but, from time to time the rules can change if special bricks are touched. Red: invert ball direction White: triple ball Yellow: smaller paddles Blue: bigger paddles Green: speed up ball Orange: change...

by Pello Altadill 04/07/2014 07:35:33 - 1541 hits

More »

Getting started with Node

Few days ago, a very dear friend of mine came up to my place with a present. It was a nodejs book. This is a new or maybe it would be more accurate to say an emergent technology which brings back an old idea that I used to hear of long time ago: a server side javascript. That was something that was supposed to exist somewhere, as it was mentioned in the prefaces of many javascript related papers: ...

by Pello Altadill 03/17/2014 23:48:44 - 1798 hits

More »

Calcular el IBAN con php

Los organismos internaciones se han vuelto a poner de acuerdo para poner unificar los números de cuenta y gracias a ello todos los programadores y DBAs del mundo ya estamos enfrascados en la tarea de adaptar programas, validaciones, campos de las BBDD y un largo etcétera. En cada país el código de cuenta corriente puede variar y a través del IBAN se intenta unificar la forma de esa cuenta de tal forma que sea validable. ...

by Pello Altadill 01/18/2014 00:01:21 - 1864 hits

More »

MessageQueue con Spring

Hace unos meses salió aquí un ejemplo de ActiveMQ sin Spring ni nada, aunque lo relevante era mostrar la configuración y uso del servidor de mensajes. Vamos ahora a hacer exactamente lo mismo pero utilizando Spring. Cosa que tenía pendiente desde entonces. Al igual que suce...

by Pello Altadill 01/06/2014 00:08:52 - 1868 hits

More »

Acceder a web desde Android con java.net

Accceso a Web desde Android Las aplicaciones para móviles se podrían dividir en tres grandes grupos: las que se ejecutan totalmente de forma local, las que tienen toda la información en la web y las que combinan las dos cosas. Si tenemos que acceder a la web desde Android y teniendo en cuenta que lo hacemos con java tenemos dos opciones por defecto: Usar las librerías básicas de java.net Usar HttpClient HttpClient la librería de Apache ...

by Pello Altadill 11/23/2013 10:36:35 - 2067 hits

More »