Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptHow to share code between Node.js and the browser?

How to share code between Node.js and the browser?

In this article, we will explore how to write JavaScript modules that can be used by both the client-side and the server-side applications.
We have a small web application with a JavaScript client (running in the browser) and a Node.js server communicating with it. And we have a function getFrequency() which is to be used by both server and client to get the frequency of characters in a given string. We want to create a single set of methods which can facilitate the task at both the ends.
Approach: 
Writing code for client-side (running in the browser) differs a lot from server-side Node.js application. In client-side we mainly deal with DOM or web APIs like cookies, but these things don’t exist in Node. Other reasons why we cannot use node modules at the client side is that the node uses the CommonJS module system while the browser uses standard ES Modules which has different syntax.
In node, we use module.exports to expose functionality or property. However, this will break in the browser, as the browser cannot recognize exports. So, to make it work, we check if exports is defined, if not then we create a sensible object for exporting functions. In the browser, this can be achieved by creating a global variable that has the same name as that of the module.
The structure of the module will look something like as follows: 
sampleModule.js 
 

javascript




// Checking if exports is defined
if(typeof exports === 'undefined'){
   var exports = this['sampleModule'] = {};
}
  
// The code define the functions,
// variables or object to expose as
// exports.variableName
// exports.functionName
// exports.ObjectName
  
// Function not to expose
function notToExport(){ }
  
// Function to be exposed
exports.test(){ }


The above format has a problem that anything we define in sampleModule.js but not exported will be available to the browser, i.e. both the function notToExport() and test() will work outside this file. So, to overcome this we wrap the module in a closure.
sampleModule.js 
 

javascript




(function(exports) {
    
   // The code defines all the functions,
   // variables or object to expose as:
   // exports.variableName
   // exports.functionName
   // exports.ObjectName
  
}) (typeof exports === 'undefined'? this['sampleModule']={}: exports);


Example: Let us make a sample module which contains a method ‘getFrequency’ to count the frequency of characters in a string. 
 

  • sharedModule.js 
     

javascript




// All the code in this module is
// enclosed in closure
(function(exports) {
  
    // Helper function
    function toLC(str) {
        return str.trim().toLowerCase();
    }
  
    // Function to be exposed
    function getFrequency(str) {
        str = toLC(str);
        var freq = [];
        for(var i = 0; i < 26; i++) {
            freq.push(0);
        }
  
        for(var i = 0; i < str.length; i++) {
            freq[str.charCodeAt(i)-97]++;
        }
        return freq;
    }
  
    // Export the function to exports
    // In node.js this will be exports
    // the module.exports
    // In browser this will be function in
    // the global object sharedModule
    exports.getFrequency = getFrequency;
      
})(typeof exports === 'undefined'?
            this['sharedModule']={}: exports);


  • nodeApp.js 
     

javascript




// Simple node.js script which uses sharedModule.js
  
// Get module.exports of sharedModule
const utilities = require('./sharedModule');
  
// Print frequency of character
console.log(utilities.getFrequency("GeeksForGeeks"));


  • clientApp.js 
     

javascript




// Use functionality getFrequency which
// is available in sharedModule object
document.write(this.sharedModule.getFrequency("GeeksForGeeks"));


  • index.html 
     

html




<script src="./sharedModule.js"></script>
<script src="./clientApp.js"></script>


Steps to Run the program: 
 

  • Copy and paste all the code with their respective file names and make sure all the files are in same the directory.
  • Open terminal in the same directory and execute ‘node nodeApp.js’.
  • Open index.html in any browser.

Output: 
 

  • Output on node.js console: 
     
[ 0, 0, 0, 0, 4, 1, 2, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0 ]
  • Output on browser: 
     

RELATED ARTICLES

Most Popular

Recent Comments