How to share code between Node.js and the browser?
Last Updated :
06 Sep, 2021
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.Â
Â
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);
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"));
javascript
// Use functionality getFrequency which
// is available in sharedModule object
document.write(this.sharedModule.getFrequency("GeeksForGeeks"));
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 ]
Similar Reads
What is the Relationship between Node.js and V8 ?
Node.js and V8 are closely related, with V8 being a fundamental component of Node.js that significantly influences its capabilities and performance. Understanding their relationship involves delving into the roles each plays and how they interact within the context of server-side JavaScript executio
10 min read
How to Separate Routers and Controllers in Node.js ?
In a Node.js application, especially when using the Express framework, separating routers and controllers is a common practice to keep the codebase organized, maintainable, and scalable. This separation of concerns ensures that routing logic is kept separate from the business logic, making the appli
4 min read
How to Use math.js in NodeJS And Browser?
Math.js can be used to perform complex mathematical computations in both NodeJS and browser environments. It is a powerful library that supports a wide range of mathematical functions, including algebra, calculus, and statistical operations. By integrating math.js into your projects, you can handle
3 min read
How to share code between files in JavaScript ?
JavaScript is a powerful and popular programming language that is widely used for web development. One of the key features of JavaScript is its ability to share code between files. This can be useful for organizing large projects, reusing code, and maintaining code quality. In this article, we'll se
6 min read
How Node.js works behind the scene ?
Node.js is the JavaScript runtime environment which is based on Googleâs V8 Engine i.e. with the help of Node.js we can run the JavaScript outside of the browser. Other things that you may or may not have read about Node.js is that it is single-threaded, based on event-driven architecture, and non-b
5 min read
How to set up your Node.js and Express development environment?
In this article, we are going to learn how to set up your NODE JS and Express JS development environments. Node JS and Express JS development environments are used to write the code for the server side. Server-side code is responsible for handling HTTP requests and API endpoints of your application.
4 min read
How to Use Node.js for Backend Web Development?
In the world of website design nowadays, NodeJS is a supportive tool for making capable backend systems. Whether you are an experienced web designer or just beginning out, NodeJS can upgrade your aptitude and help you in building extraordinary websites. This guide will show you how to use NodeJS to
8 min read
How to Generate/Send JSON Data at the Client Side ?
Javascript Object Notation (JSON) is a widely used format for sending and receiving data to or from the server. In this article, we will use fetch API to send and receive data from the NodeJS server. Advantages of JSON: Because of its easy and small syntax, it executes the response in a faster way.
3 min read
How to Build Middleware for Node JS: A Complete Guide
NodeJS is a powerful tool that is used for building high-performance web applications. It is used as a JavaScript on runtime environment at the server side. One of Its key features is middleware, which allows you to enhance the request and response object in your application.Building middleware for
5 min read
Difference between Node.js and Ruby on Rails
Before stepping into a new project, the software developing team goes through a severe discussion in order to choose the best language, framework, or methodology for their project. As we are aware, the different technologies have their different pros and cons and similarly the technology which is lo
8 min read