JavaScript

Search for '{{search_term}}'

JavaScript module to run both in a browser and in Node.js

CMOS is the Code-Maven Open Source podcast that also includes video interviews. Subscribe to this feed RSS feed with your Podcast listener app or via iTunes iTunes.

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

examples/js/node_and_web/calc.js

(function(){
    "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,
        });
        
    }();

}).call(this);

We can see it working in Node:

examples/js/node_and_web/calc_test_node.js

console.log('calc_test_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 
calc_test_node
7
4
0.01

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

examples/js/node_and_web/calc_test_web.js

console.log('calc_test_web');
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:

examples/js/node_and_web/calc_test_web.html

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

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

Comments

In the comments, please wrap your code snippets within <pre> </pre> tags and use spaces for indentation.
comments powered by Disqus