Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Just today I devised a pretty solid method to build a fairly complex node.js app while keeping it simple, maintainable and scalable.

I like the way node kind of enforces modularity, but for something as complex as the backend (super-flexible api for a frontend dbms) required for my project, it would save a lot of time/effort/ugliness-of-code to have a few objects on the global scope while allowing individual parts to be split up into their own files; e.g., a few utility functions, String/Array.prototype functions, a socket.io instance, and a redis client instance, among other things.

And to make things manageable and more extensible all while minimizing duplicate code, I ended up using John Resig's "Simple Javascript Inheritance": http://ejohn.org/blog/simple-javascript-inheritance/. I like being able to simply call Class.extend({}) to create/extend any class with access to its "super" functions. Each class is contained within its own file, of course.

The method is pretty simple: 1) Organize and order the files like you would on a client (web browser) where "global" variables are allowed. 2) Use some program to concatenate the files in the correct order into a single node app.js file for testing or production.

I'm currently using a batch script (yes, I use Windows :P) that looks something like this:

  del app.js
  type global.js >> app.js
  type appBegin.js >> app.js
  type loggur.js >> app.js
  type classes\Class.js >> app.js
  type classes\Client.js >> app.js
  type get.js >> app.js
  type post.js >> app.js
  type set.js >> app.js
  type socketsOn.js >> app.js
  type appEnd.js >> app.js

Don't get me wrong, node's module system is used when it makes the most sense. But for what I need to do, this works perfectly. It doesn't promote spaghetti code the least bit; everything is easy to read and follow (could even call the code pretty!); it's 100% clear which objects are shared (especially since most files contain a single object or class); and as long as the method is used consistently, you get all the benefits of node/socket.io while maintaining cleanliness and scalability.


You don't even need to concatenate the files, just use the globals object + require() normally.


The key is that I'm not actually polluting the global namespace. I also feel like using the globals object + require() would still be ugly/messy.


Global objects are not as much a sin as in the browser, since the environment is usually completely under your control. And of course, you wouldn't use more than a couple.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: