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
// 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
(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
// All the code in this module is// enclosed in closure(function(exports) {// Helper functionfunctiontoLC(str) {returnstr.trim().toLowerCase();}// Function to be exposedfunctiongetFrequency(str) {str = toLC(str);varfreq = [];for(vari = 0; i < 26; i++) {freq.push(0);}for(vari = 0; i < str.length; i++) {freq[str.charCodeAt(i)-97]++;}returnfreq;}// 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 sharedModuleexports.getFrequency = getFrequency;})(typeofexports ==='undefined'?this['sharedModule']={}: exports);chevron_rightfilter_none - nodeApp.js
// Simple node.js script which uses sharedModule.js// Get module.exports of sharedModuleconst utilities = require('./sharedModule');// Print ferquency of characterconsole.log(utilities.getFrequency("GeeksForGeeks"));chevron_rightfilter_none - clientApp.js
// Use functionality getFrequency which// is available in sharedModule objectdocument.write(this.sharedModule.getFrequency("GeeksForGeeks"));chevron_rightfilter_none -
index.html
<scriptsrc="./sharedModule.js"></script><scriptsrc="./clientApp.js"></script>chevron_rightfilter_none
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:

Recommended Posts:
- Nodejs | Automatic restart NodeJs server with nodemon
- Nodejs | DNS
- Nodejs | Jimp
- Introduction to NodeJS
- Web-Socket in NodeJS
- Nodejs | DNS | setServers()
- Dockerizing a simple Nodejs app
- Encrypting Data in NodeJS
- Nodejs | Web Crawling using Cheerio
- Difference between NodeJS and AngularJS
- Nodejs – Connect Mysql with Node app
- Cowsay in Nodejs using Requests library
- NodeJs - Handling invalid routes
- Signup Form Using Nodejs and MongoDB
- NodeJS | Building simple REST API in express
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



