2.09.2012

nomination part 3 - app.js and log

Version en espaƱol


This post is part of the series about creating an app with node.js, express for Facebook



OK, let me start rewriting a little bit our app.js, which holds all the routes for the app, we are going to separate the routes into diff files so we don't end up with a very long and complicated file, and lets add the log module to start logging some stuff.

Lets begging updating our package.json by adding the log module:

, "log" : "1.2.0"

We end up with:

{
 "name": "nomi-nation"
 , "version": "0.0.1"
 , "private": true
 , "dependencies": {
 "express": "2.5.2"
 , "jade": ">= 0.0.1"
 , "express-messages" : ">= 0.0.2"
 , "facebook-js" : "1.0.1"
 , "mongoose" : "2.4.8"
 , "log" : "1.2.0"
 }
}

and later from our root folder of our app we do:

npm install -d

With this command we install all our dependencies, in this case only the log was new so you will see it in node_modules folder now.

Lets add the vars required to our app.js for logging, this is at the top of the app.js file:

Log = require('log'),
 log = new Log(),
 fs = require('fs');

In the configuration part lets configure our log, depending on the environment, this is the debug part:

log.level = Log.DEBUG;
 log.stream = fs.createWriteStream('logs/dev.log', { flags: 'w' });

for production change the file name and the "log.level" to "fine" or something that works for you.
Lets add a simple log in the route "/":

log.notice('landed on:' + new Date());

Sweet, logging is ready, lets change the routes to some other files, is really simple actually, first we need to create a folder called "routes", you can call it whenever you want, and we will add a file called "index.js" this will hold our main routes, the name of the file is also whatever you want, index file will be something like this:

/**
 * Main routes
 *
*/
module.exports = function(app, log){
 /*
 * GET home page.
 */
 app.get('/', function(req, res){
 log.notice('landed on:' + new Date());
 res.render('index', { title: 'Express' });
 });
};

Well we only have one route now, this will change in later posts, but lets see what we did here:
modle.exports its to tell node that we are exporting the function that hold several routes, in this case only one, and we are expecting the app variable that holds the actual app, and the log variable that holds the reference for our logging needs.

Back to our app.js, lets erase the route "/" that we have there and lets add the routes file/module:

// Routes
require('./routes/index')(app, log);

We are requiring out index file that export the function with the main routes, and we are passing the app and the log.

We dont create another log variable inside index.js because it will then initialize all the logging again.

We are done, right now we are just setting up our environment for later releases

You can see the code in github:

https://github.com/nodejs-mexico/nomi-nation

Greetings 

No comments:

Post a Comment