Node projects style guide
We suggest the next architecture for your node project, these suggestons are to help you make it understandable.
.
├── index.js
├── globals.js
├── conf.js
├── lib/
└── cfg/
└── development.js
└── production.js
To know which is the main file on your project, we recommend name it as index.js simulating the main file of web project, also in the index.js file, we suggest declare the root directory change code, to set the project directory on the function process.cwd().
//Change the root path for all project
process.chroot(__dirname);
Use a folder called cfg with many files as you require to manage different params for specific environments.
For example:
.
└── cfg/
└── development.js
└── production.js
└── testing.js
When you have the cfg folder, you must write a file that include code to manage the files to return analyzing the NODE_ENV variable on your OS, which you could set as "development", "production" or "testing".
module.exports = (function(env) {
return require('./cfg/' + env + '.js');
})((process.env.NODE_ENV || 'development'));
//Node libraries import
var http = require('http'),
path = require('path');
//3th party libraries
var express = require('express'),
redis = require('redis');
//Local libraries
var mylib1 = require(process.cwd() + '/lib/mylib1'),
mylib2 = require(process.cwd() + '/lib/mylib2');
//Write your code below
We suggest you to write a file global.js that helps you to keep global variables, all the project along and use it on your response sending.
The content in global.js, , for example:
module.exports = function(req) {
var data = {
currencies: ['USD', 'MXN', 'EUR'],
yearsLeft: (function(left) {
var currentYear = new Date().getFullYear();
var years = [];
for (var i = 0; i < left; i++) {
years.push(++currentYear);
}
return years;
})(20)
};
return data;
}