Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to structure nodejs code properly

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?

like image 967
John Hamelink Avatar asked May 20 '11 08:05

John Hamelink


People also ask

Which architecture is best for Node JS?

Node. js uses 'Single Threaded Event Loop' architecture to handle multiple concurrent clients.


2 Answers

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.)

like image 83
Rob Raisch Avatar answered Nov 09 '22 23:11

Rob Raisch


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

like image 20
KooiInc Avatar answered Nov 10 '22 00:11

KooiInc