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?

11/14/2016 9:30:42 PM

Accepted Answer

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):


    // 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.

8/29/2016 9:22:57 PM

Epeli has a nice solution here that even works without the library, just put this in a file called share.js


  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');


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


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow