How to structure nodejs code properly
I've been playing with node.js for a wh开发者_开发技巧ile, and I've really come to appreciate how awesome it is. However, one thing I'm struggling to understand is how I should structure my code so that it is maintainable. Most tutorials I've seen on the internet have all the JS in one file, which is hardly a nice way to manage your code. I am aware there is no such thing in real-terms as a "class" in javascript, but is there a (standard) way for me to format my code for maintainability in the same way I'd structure a PHP project, for example?
I'd add that as far as maintainability goes, I believe the typical style of deeply-nesting callbacks using closures is the single greatest impediment to the understandability of Node programs, as well as being completely unnecessary.
For every:
a.doSomething(val, function(err,result){
b.doSomethingElse(result,function(err,res){
...
});
});
There is always a:
a.doSomething(val, onDoSomething);
function onDoSomething(err,res) {
...
}
My rule of thumb is: a new non-closure callback function is required for anything over three levels of nesting.
(Node.js really needs a style manual.)
Afaik you can use require
to include your own js files (containing exported methods) using:
var req = require('./someJsFile');
Within someJsFile.js
you can export methods like this:
exports.someMethod = function(){ /*...*/ };
And in your main file you can address such a method using req.someMethod()
So this way you can split up your code in different files, which you require
from some central js file.
Here is an article explaining node.js require
After you learned how require works in node.js (pretty straightforward), as suggested by Kooilnc
You can take a look at the source code of the modules available for Node.js:
https://github.com/joyent/node/wiki/modules
If you're planning to use Express (one of the most robust node.js framework out there) to develop your first node applications, you can take a look at its specific samples here:
https://github.com/visionmedia/express/tree/master/examples (there's also an mvc sample)
精彩评论