One of the selling points of using Node.js to write the back-end of your application is that in that case you use the same programming language in the back-end as you use in the front-end. Then it is easy to share code between the two.

The question then, how can one write a library in JavaScript that can be used both in Node.js and in the web client.

This is a simple library with two methods: add and div, and an attribute version It uses this which refers to the Window object when running in the browser and to the global object when running under Node.js


    "use strict";

    this.Calc = function () {
        return Object.freeze({
            add: function(x, y) { return x + y; },
            div: function(x, y) { return x / y; },
            version: 0.01,


We can see it working in Node:


var c = require('./calc');
console.log(c.Calc.add(2, 5)); // 7
console.log(c.Calc.div(8, 2)); // 4
console.log(c.Calc.version);   // 0.01

$  node calc_test_node.js

We can see it working in the web as well. For that we need to write some JavaScript code:


console.log(Calc.add(2, 3));    // 5
console.log(Calc.div(14, 2));   // 7
console.log(Calc.version);      // 0.01

and then we have to load first the calc.js and then the JAvaScript file that uses the Calc object:


<script src="calc.js"></script>
<script src="calc_test_web.js"></script>

If you click on "Try" you will see it working. Just remember you need to open the JavaScript console to see anything.