How to Share Code Between Node.Js and the Browser

How can I share code between Node.js and the browser?

If you want to write a module that can be used both client side and server side, I have a short blog post on a quick and easy method: Writing for Node.js and the browser, essentially the following (where this is the same as window):

(function(exports){

// Your code goes here

exports.test = function(){
return 'hello world'
};

})(typeof exports === 'undefined'? this['mymodule']={}: exports);

Alternatively there are some projects aiming to implement the Node.js API on the client side, such as Marak's gemini.

You might also be interested in DNode, which lets you expose a JavaScript function so that it can be called from another machine using a simple JSON-based network protocol.

Sharing Code between Node.js and the browser

You need something like this:

function someFunctionName() {

// Common functional

if (typeof module !== 'undefined' && module.exports) {
// Do something only in Node.JS
} else {
// Do something else in the browser
}

// Common functional
}

Sharing a class between Node.js and the browser

NowJS is a pretty elegant way to share variables and functions between client JS and Node JS through an automatically sync'ed shared namespace.

There's also dnode, which the author comments on in response to a posting about NowJS here: http://news.ycombinator.com/item?id=2316079



Related Topics



Leave a reply



Submit