Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am creating a small application with a JavaScript client (run in the browser) and a Node.js server, communicating using WebSocket.

I would like to share code between the client and the server. I have only just started with Node.js and my knowledge of modern JavaScript is a little rusty, to say the least. So I am still getting my head around the CommonJS require() function. If I am creating my packages by using the 'export' object, then I cannot see how I could use the same JavaScript files in the browser.

I want to create a set of methods and classes that are used on both ends to facilitate encoding and decoding messages, and other mirrored tasks. However, the Node.js/CommonJS packaging systems seems to preclude me from creating JavaScript files that can be used on both sides.

I also tried using JS.Class to get a tighter OO model, but I gave up because I couldn't figure out how to get the provided JavaScript files to work with require(). Is there something am I missing here?

like image 212
Simon Cave Avatar asked Jul 12 '10 00:07

Simon Cave


People also ask

Can you run NodeJS code in browser?

Thanks to some creative engineers, it is now feasible to use Node. js modules in browsers, but not directly. Being able to call Node. js modules from JavaScript running in the browser has many advantages because it allows you to use Node.


2 Answers

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.

like image 98
Caolan Avatar answered Sep 17 '22 15:09

Caolan


Epeli has a nice solution here http://epeli.github.com/piler/ that even works without the library, just put this in a file called share.js

(function(exports){    exports.test = function(){        return 'This is a function from shared module';   };  }(typeof exports === 'undefined' ? this.share = {} : exports)); 

On the server side just use:

var share = require('./share.js');  share.test(); 

And on the client side just load the js file and then use

share.test(); 
like image 29
broesch Avatar answered Sep 17 '22 15:09

broesch