Using and Running Node.js Modules in The Browser
Receive new NodeJS tutorials.
In this quick tutorial, we'll learn to use and run Node.js modules in the browser.
Node.js has the largest repository of open source modules in the world, which solve many common and uncommon development problems. You can easily find a module for almost any functionality you are looking for, so you can concentrate on solving your specific requirments, without re-inventing the wheel, and boost your productivity.
The Node.js runtime doesn't exist on the client, you have only the browser which can't make use of Node.js modules. We are hearing you saying, what a big waste!
But guess what? Thanks to some clever developers, It's now possible to use Node.js modules in browsers, not directly but can be done.
Browsers don't have the require/export or the module import system which exists on Node.js platform; Browserify lets use the Node.js import system.
Suppose you have written your application source code using require syntax to import a useful Node.js module. Now to be able to use your application in the browser with no error you need to use Browserify and run the following command:
browserify app.js -o bundle.js
How To Use Browserify?
So first of all lauch your command line terminal and type the famous npm install command to install browserify:
npm install -g browserify
Next create your example project folder
Next you should install the module you want to use or to convert to browser compatible script
npm install -g ytdl-core
main.js require the module as you do normally with node.js modules:
var yt = require('ytdl-core'); console.log(yt);
Now let the magic begins, call browserify with the input is
main.js and give it a name for the output
browserify main.js -o ytdl.js ...
Now you can use your script as easily as using a script tag
<script src="ytdl.js"></script> ...
In this tutorial, we have seen how to use Browserify to use Node.js modules in the browser.
Note: We also publish our tutorials on Medium and DEV.to. If you prefer reading in these platforms, you can follow us there to get our newest articles.
You can reach the author via Twitter:
About the author
Get our Learn Angular 8 in 15 Easy Steps ebook in pdf, epub and mobi formats, plus a new Angular 8 tutorial every 3 days.
Read our other tutorials
- Angular Tutorial
- Laravel 6 Tutorial
- React Tutorial
- React Hooks Tutorial
- React Native Tutorial
- Webpack Tutorial
- PHP Tutorial
- Django Tutorial
- Java Spring Tutorial
- Rails 6 Tutorial
- Ionic 4 Tutorial
- TypeScript Tutorial
- Bootstrap 4 Tutorial
- Electron Tutorial
- Cordova Tutorial
- HTML Tutorial
- GraphQL Tutorial
- CSS Grid Layout Tutorial
- PWA Tutorial