Bringing Node.js Modules to The Browser
In this quick tutorial, we'll learn to use 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 reinventing the wheel and boost your productivity.
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.