Node Js Modules

A Module or a library is a set of functions that can be imported and can be used for performing various processes in Node js.
Node Js Inbuilt Modules
When we install Node js, we get a list of in built Node Js modules which we don’t need to install and they come with the Node installers itself.
Some of the popular and highly used node js in build modules
|
assert buffer crypto events
|
Fs http https querystring
|
readline timers util zlib
|
Node Js Core Modules
Below is the list of Node.Js core modules
http : Used for creating http server
url : Used for URL parsing and resolution
querystring : Used for getting data from query string
path : Used to handle files
fs : Used for handling files, I/O
util : Used for processing some utility functions
How to create my own module
We can create our own modules and use it in our application.
- Create a javascript file ‘example3.js’ and add below snippets
exports.printDate = function() {
console.log("This is a print statement from custom Module");
return " Today Date " +Date();
}
By using exports, we are defining that the function is available outside the file also.
- Now let’s use this file. Let’s open our example1.js and update it with the below code.
var ex = require('./example3');
console.log("Testing custom module" + ex.printDate());
here, we are first importing the custom module and then using it below. The “./” path means that the module is in the same folder. We can specify custom paths if the modules are in different folders.
- Let’s run the example1 code now.
c:\test>node example1.js
This is a print statement from custom Module
Testing custom module Today Date Sat Dec 28 2019 12:12:26 GMT+1100 (Australian Eas
tern Daylight Time)
There are many external modules that can be installed and make our node applications very simple.
Below is the list of popular node modules that are extensively used and recommended.
Popular Node js Modules
express.js: A leading node js web application server framework for creating web and mobile applications. It provides a structure for building big functional applications. It provides HTTP helpers for caching and redirection also.
async.js : It is a very popular node module used in communication between javascript and web pages.It can speed up pages by delaying render blocking javascript. It enables us to load js content in parallel/async with other web components loading and can speed up websites.
Socket.io : It helps in building real-time bidirectional event-based communication applications. It can be seen in various chatting applications and social streams for getting latest events and updates.
Babel.js : A very popular JavaScript transpiler that converts edge JavaScript into plain old ES5 JavaScript that can run in any browser (even the old ones). It has now added many conversion of various javascript types.
Restify : It is a lightweight framewor for building REST APIs
Loadash : It provides support to work with complex object, like arrays, numbers and simplifies javascript code.
Body-parser: It can parse the incoming request before handlers and available under req.body property.
Mocha : A javascript test framework running on node.js and the browser for asynchronous testing.
Bower: Keeps track of all the packages and making sure they are up to date.
How to Install node modules
Using node package manager (npm), we need to first install the module.
Let’s install express
We need to below command
npm install express
npm install express
npm WARN enoent ENOENT: no such file or directory, open 'c:\test\package.json'
npm WARN test No description
npm WARN test No repository field.
npm WARN test No README data
npm WARN test No license field.
+ [email protected]
added 50 packages from 37 contributors and audited 126 packages in 31.896s
found 0 vulnerabilities
Installing at local vs global
Npm allows us to install node modules at local and global locations
- Local -> npm install <package>
This will install the package in the folder where we are running and is available in that path only
- Global -> npm install –g <package>
This will have the package installed in the node installation directory and the module is available in any folder in the system.
Ideally, we should use the local version as we can have multiple applications in our system and all can have their own version of packages if required. Updating a global package will require us to test or fix all the applications in our system.
Now let’s verify if the express is installed and is available for use
Create an example4.js and put the below code in that
try {
console.log(require.resolve("express"));
} catch(e) {
console.error("express is not found");
process.exit(e.code);
}
Now run the node command
c:\test>node example4.js
c:\test\node_modules\express\index.js
Ways of finding installed packages
We can run below commands to find the installed packages
For locally installed packages:npm list –depth 0
c:\test>npm list --depth 0
c:\test
`-- [email protected]
For globally installed packages:npm list –g –depth 0
c:\test>npm list -g --depth 0
[email protected] C:\Users\x\AppData\Roaming\npm
+-- [email protected]
+-- [email protected]
+-- [email protected]
+-- [email protected]
+-- UNMET PEER DEPENDENCY es6-shim@^0.35.0
+-- [email protected]
+-- [email protected]
+-- [email protected]
`-- UNMET PEER DEPENDENCY zone.js@^0.6.12
Playing with npm package installer
- If running behind a proxy or no internet
c:\test>npm install mocha
npm ERR! code ENOTFOUND
npm ERR! errno ENOTFOUND
npm ERR! network request to http://registry.npmjs.org/mocha failed, reason: geta
ddrinfo ENOTFOUND registry.npmjs.org registry.npmjs.org:80
npm ERR! network This is a problem related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settin
gs.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly. See: 'npm help config'
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\X\AppData\Roaming\npm-cache\_logs\2019-12-28T0
3_06_32_444Z-debug.log
- If the package already exists
c:\test>npm install express
npm http fetch GET 304 http://registry.npmjs.org/express 236ms (from cache)
npm WARN saveError ENOENT: no such file or directory, open 'c:\test\package.json
'
npm WARN enoent ENOENT: no such file or directory, open 'c:\test\package.json'
npm WARN test No description
npm WARN test No repository field.
npm WARN test No README data
npm WARN test No license field.
npm http fetch POST 200 http://registry.npmjs.org/-/npm/v1/security/audits/quick
494ms
+ [email protected]
updated 1 package and audited 286 packages in 1.258s
found 0 vulnerabilities
- No package defined
c:\test>npm install
npm WARN saveError ENOENT: no such file or directory, open 'c:\test\package.json
'
npm WARN enoent ENOENT: no such file or directory, open 'c:\test\package.json'
npm WARN test No description
npm WARN test No repository field.
npm WARN test No README data
npm WARN test No license field.
npm http fetch POST 200 http://registry.npmjs.org/-/npm/v1/security/audits/quick
789ms
audited 286 packages in 1.4s
found 0 vulnerabilities
- Incorrect package defined
It will throw 404 error
c:\test>npm install nonexistpackage
npm http fetch GET 404 http://registry.npmjs.org/nonexistpackage 298ms
npm http fetch GET 404 http://registry.npmjs.org/nonexistpackage 818ms
npm ERR! code E404
npm ERR! 404 Not Found - GET http://registry.npmjs.org/nonexistpackage - Not fou
nd
npm ERR! 404
npm ERR! 404 'nonexistpackage@latest' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\X\AppData\Roaming\npm-cache\_logs\2019-12-28T0
3_12_47_717Z-debug.log
npm install vs npm update:
npm update is used when we already have the module installed with its dependencies.
npm install : It installs all modules that are listed on package.json file and their dependencies.
npm update : It updates all packages in the node_modules directory and their dependencies.
Samples:
npm install express : It will install only the express module and its dependencies.
npm update express: It will update express module and do not update its dependencies.
Other popular package managers:
Yarn : Built by facebook to fix scalability and increase speed for package installation
Pnpm : pnpm is a popular manager for reducing disk space by using one copy of the package on disk.
Frequently Asked Questions
What is the crypto module in Node.js?
The crypto module in Node.js is used in cryptographic functionality.
What is package.json?
package.json contains metadata of the project. It also helps npm to find the project’s dependencies.
Some of the fields are: name, name, description, author, and dependencies
What are the most popular modules in Node.js?
Some of the most popular modules:
express
async
browserify
socket.io
bower
grunt
What is the use of module.exports in Node.js?
module.exports makes the functions accessible into the other javascript files. It makes these functions as public and other files can use these functions as a library function.
What is DNS module in Node.js?
This module helps in underlying system’s name resolution and DNS lookup facilities.
Foe example:dns.lookup(url, options, callback) can provide IP address of the given url.
What is the passport module in Node.js?
Passport.js is a simple authentication middleware for Node.js. Passport.js and can be used with Express.js-based web application.It works with the application to deploy specific security strategies into the application.
What is Libuv?
Libuv is a support library of Node.js for asynchronous Input/output.
Some of the features of Libuv are:
File System Events
Child Processes
Full-featured event loop backed
Asynchronous TCP & UDP sockets
What is Q module?
Q module is used in Node.js for using promises APIs.