I've been playing with node.js for a while, 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?
Node. js uses 'Single Threaded Event Loop' architecture to handle multiple concurrent clients.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With