Module is an encapsulated code, separated from main application code with functionality that can be reused throughout your code. NodeJS provides us with various repositories of open source modules that can help us achieve various development tasks. But these modules are only useful if you’re building a server side application.
Node JS Installation
Before anything, you need to have NodeJS installed. For this visit the link by clicking on this and download the LTS (Recommended) version.
Now, to check whether NodeJS and NPM have been installed on your device you can run the following command:
How to install NodeJS module
There are two ways you can download the module, locally and globally. The difference is that the globally downloaded module can be accessed easily by all the projects on your system. Whereas, local modules can only be accessed by your current project. Command for Downloading Module Locally:
To better understand this, we’ll install the Express module, which is used for building APIs etc.
It’ll provide you with the following output.
A new folder will be created automatically by NPM by the name “node_modules”, It will store all your modules and packages.
Command for Downloading Module Globally
It’s better to install modules both locally and globally. Reason is that it’ll allow you to share the installed command and at the same time you’ll be able to protect the dependencies. Run the following command:
In the following example we’ll install dateformat package globally:
var now = new Date();
console.log(dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT"));
But this will cause an error:
Why is that? Well, the reason is that NodeJS is a server-side technology. It comes with it’s perks, but a major drawback is you can not run your module on your browser without installing some tools.
How to run modules using Browserify on Browsers
Browserify is a command line NodeJS module that allows users to write and use already existing NodeJS modules that run on the browser.
Firstly, we have to install Browserify. For installation following command needs to be run:
Now, the following command needs to be run so that you can run your application in the browser without any errors.
This command will resolve all the dependencies and combine your source code into a file that can be included with a single script tag. But note that these commands need to be run each time you make changes in your original source code.
Now, just replace the name of the source in the script tag with “bundle.js” in the html file.
<script src = "bundle.js">
Now, if your run this HTML file and open the console, it will not display any error and the result will be displayed:
In this way you can easily use your script through a single script tag inside an HTML file. Through Browserify, you can easily run your modules on browsers without any error.