Before I started learning Node.js I was happy doing my projects with PHP codeigniter. When I learned Node.js, I tried to implement the routing mechanism codeigniter use by looking up controllers file names.
This is how my Node.js app routing is:
app.get('*', function(req, res) {
// URL string -> array[]
var url = req.originalUrl.split("/");
// [0] is always empty
// [1] is controller
req.controller = url[1] || config.defaultController;
// [2] is method
req.method = url[2] || config.defaultMethod;
// [...] the rest is arguments the forementioned method
req.args = [];
for (var i = 3; i <= url.length-1; i++) {
req.args.push(url[i]);
}
// those are the controller files available
var files = fs.readdirSync("app/controllers");
// and this is the requested controller file
var targetController = req.controller + ".js";
targetController = targetController.toLowerCase();
// if file exists in arrayy : 200
if (files.indexOf(targetController) > -1) var method = nk_cRequire(targetController)[req.method]; /*global nk_cRequire*/
// if file doens't exist in array : 404
else var method = nk_cRequire("404.js").index;
// if method is not a function
if (typeof method != "function") method = nk_cRequire("404.js").index;
method(req, res, req.args);
// cheers...
});
Note: the nk_cRequire
is just a global method that used to require controllers from the controllers folder.
Creating a file called catpics.js
in the app/controllers
folder would result in creating www.host.tld/catpics
route, and creating a method of showcat
in that controller, would result in creating www.host.tld/catpics/showcat
route, then every other level will be an argument passed to this route.
This route:
www.host.tld/catpics/showcat/argument1/argument2/argument3
would pass argument1
, argument2
and argument3
as arguments to the showcats method in the catpics
controller.