Reputation: 108
I'm quite new to node.js, and pretty new to Javascript (I don't count simple animations with jQuery as js). As a web-developer, I'm moving from PHP/MySQL to Express/mongo.
I like the idea of things being neat - as long as there isn't a noticeable loss in performance. As node is so rapidly developing, I'm finding it hard to find specific opinions and answers to my routeing methods for the current version of node (Most posts I find seem to be irrelevant and older than 2 years).
|- app.js
|- routes
|- blog.js
I'm using blog.js as the gateway for all blog-related stuff. This includes registering GET and POST requests with a function, and handling page-rendering.
This is all fired up with one call.
My app.js has the following:
... //basic express installation
var db = ... //mongoose database connection
require('./routes/blog')(app, db, '/blog'); //starts the blog up
blog.js looks like this:
var db = null;
var basedir = null;
module.exports = function(app, _db, _basedir){
db = _db;
basedir = _basedir;
app.get (basedir, pages.home );
app.get (basedir + '/show/:id', pages.getBlog );
/*app.get(basedir + '/*', function(req, res) {
res.redirect(basedir);
});*/
};
var pages = {
home : function(req, res) {
// whatever
}
, getBlog : function(req, res) {
// whatever
}
}
I know this works - my question, is if this is conventional? Is it something that isn't recommended? Is it memory-wasteful? Why do people place app.gets in app.js rather than an external file? What are the current mainly used routeing methods (I develop multiple small applications all on the same server, hence my wish for my app.js to be as minimal as possible).
Upvotes: 0
Views: 948
Reputation: 17573
The way you've outlined is perfectly acceptable, and in my mind, preferred to just having one big app.js file with all your routes and everything else in it.
Many people take the separating of code much further than what you've outlined, especially when trying to follow MVC and MVC-like patterns.
For example, here's a boilerplate project I'd been working on that might even go a little overboard on separation. It's not a finished product, just something I was playing with that took some of the different bits I liked from other boilerplates, frameworks, etc. I've learned some things since then and I might adjust it at some point.
NemoJS - My node/express/mongoose/jade/stylus/twitter_bstrap boilerplate project
One thing to keep in mind is the more you separate it, the more difficult it CAN be to track down problems. Not a good enough reason for not staying organized though. Which is essentially what our goal is, right?
Upvotes: 1