It is my first node.js app. I use http://www.nodebeginner.org/ as example and http://lokijs.org/ as in-memory db. So, i have problem with code orgatization. Now it is looks like following:
index.js
var server = require('./server');
var router=require('./router');
var reqHandler=require('./handler');
var loki=require('lokijs');
var db = new loki('world.json');
var handle={
'/getById':reqHandler.getById
};
db.loadDatabase({},function(){
server.start(router.route, handle,db)
});
server.js
var http = require('http');
var url = require('url');
function start(route,handle,db){
http.createServer(function (req, res) {
route(req, res, handle,db);
}).listen(8080);
}
exports.start=start;
router.js
var url = require('url');
function route(req,res,handle,db) {
var pathname = url.parse(req.url).pathname;
if (typeof handle[pathname] === 'function') {
handle[pathname](res, req,db);
} else {
//process error
}
}
exports.route = route;
handler.js
var url = require('url');
var loki=require('lokijs');
var querystring=require('querystring');
function getById(res, req,db){
//process req. send response
//HERE db MUST BE ACCESSIBLE
}
exports.getById=getById;
With current code structure I have to pass db variable from the most begining index.js to the last handler.js. It seems like not brilliant solution for me.
Can anybody help me with it? Thx in advance.