Node js Module

In Javascript, there is no way to include modules. This problem is solved in Node.js. We can place simple or complex functionality in a separate entity, that is module. We can reuse this functionality throughout the node.js applications.

How to use Node.js module

Using built-in modules in your API

Node.js has predefined set of modules, which we can easily include in our api. By using require method, you can use this built-in module using npm in api.

This is the list of most popular node.js built-in modules -

Module Description
buffer Used to handle binary data.
events Used to handle events.
fs Used to handle the file i/o system.
http Used to create Node.js http server.
https Used to create Node.js secure http server.
path Used to handle file path.
events Used to handle the occured events.
querystring Used to deal with query string.
stream Used to handle the data streaming.
url Used to parse URL strings.
util Used to include the utility functions.
For example -

var http = require("http");

All the properties and methods of http module are now available in 'http' object.


Create your own module

In Node.js, 'exports' keyword is used to export an object.

If you want your module to be a specific object type use module.exports and if you want your module to be a typical module instance, use exports.

module.exports is a real thing and exports is only a helper.

To create your own module, first create a directory name 'samplemod' and cd to it.

mkdir samplemod
cd samplemod

Now within samplemod directory, create a file name commonfunc.js and copy & paste this code -


commonfunc.js
exports.adddata = function(a1, a2) {
	return a1 + a2;
};
exports.getDate = function(){
  var datetime = Date();  
  return datetime;	
};
By using exports, we have written some methods in commonfunc module.

Now create a file name sample.js and copy & paste this code, also take care to provide the right module file path within the require function.

var getfunc = require("./samplemod/commonfunc.js");
var getsum = getfunc.adddata(14, 29);
var currentdate = getfunc.getDate();
console.log('Sum of 14 and 29 :'+ getsum);
console.log('Current date :' + currentdate);

Open cmd and run this code as -
>node sample.js
custom nodejs module

How to make installable module

To make the module installable or NPM package follow these instructions -

1. Rename commonfunc.js to index.js
2. create a file name package.json

Copy and paste this code in package.json file -

{
  "name": "samplemod",
  "version": "1.0",
  "author": "",
  "private": true
}

3. Now create a npm package, execute the pack command in the directory.

$ cd
$ npm pack samplemod


Read more articles


General Knowledge



Learn Popular Language