11

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?

3 Answers 3

12

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

1
  • 2
    I totally second you on the style manual. I'm going to suggest it on the mailinglist! Commented May 20, 2011 at 19:59
7

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

2

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.