How do I make Javascript suitable for the browser side?

I'm currently writing a node.js app which is a simple Snake/Tron style game, however I've written classes that I want to use on the server side and the browser side (maps of pixels). I've got a line for the node side which is:

module.exports = Map;

But this doesn't work on the browser side (I get a message about module being undefined), so the map doesn't load and my game doesn't draw to the screen.

I have already tried having a line before this like:

if (!document)
    module.exports = Map;

But this crashes node with "ReferenceError: document is not defined". Is there any way I can use the same code on the server side and client side?

Browsers dont have the commonJS spec that node does. You can try using something like Require.js which is a module loader. It can be used both client side and in nodejs.

Another option is Browserify.

if (typeof module !== 'undefined') {
  module.exports = foo;
} else {
  this.foo = foo; // or window.foo
}

For string.js, I just simply do:

if (window) {
  //you are in browser
} else {
  // you are in Node.js
}

Hope that helps.