0

I've written a js lib for my client to send commands directly to a rmi'ish server. It works nice but now I have to write a bit of server code to connect to the same server. That's why I would like to try Node.js. However I have some difficulty's grasping the concepts.

I would like my libraries to work on the brouwser (chrome, firefox and ie) but also be usable on Node.js, (with small motifications). That way I don't have to maintain 2 chucks of code that are almost the same.

How ever on a brouwser system you just declare a namespace and stuff all functionality in there. In node.js I use require to load my file and stuff the variables it exports into a variable.

for example './m4a.structure.js' sets up a global m4a.structure. and './m4a.cmd.js' uses that structure to generate a butch of methods (that work as proxy's to send stuf to the server). Finaly there is a './jquery.m4a.initialize.js' that bind the stuff to jquery to send the request out and handle the cash and stuff like that.

The first 2 files contain information that is still changing rapidly (week to week) so I would like them to remain usable on both the browser and the Node.js deamon bit. The last file off course isn't that big and rather browser specific therefor i won't mind (and even expect) if I can't port that.

I hope to have been clear and that you can help me a bit.

1 Answer 1

4

The simplest way to build a module which is usable as e.g. a node.js module and in the browser is this:

var Foo = function() {
};

Foo.prototype.bar = function() {
};

if(typeof exports !== 'undefined') {
  // Node.js or similar
  exports.Foo = Foo;
} else {
  // Browser -- this is window
  this.Foo = Foo;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Addy Osmani has written a great article about all the different loader frameworks.
In node, this refers to the module, so you can export the function with the same this.Foo = Foo; for the browser.

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.