0% found this document useful (0 votes)
9 views12 pages

NodeJS Modules

Node.js is a JavaScript runtime environment that utilizes a modular architecture, allowing developers to create reusable code pieces called modules. There are three types of modules in Node.js: core modules, local modules, and third-party modules, each serving different purposes in application development. The document also covers how to load and use these modules, as well as how to manage packages using Node Package Manager (NPM).

Uploaded by

Adarsh Yograaj
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views12 pages

NodeJS Modules

Node.js is a JavaScript runtime environment that utilizes a modular architecture, allowing developers to create reusable code pieces called modules. There are three types of modules in Node.js: core modules, local modules, and third-party modules, each serving different purposes in application development. The document also covers how to load and use these modules, as well as how to manage packages using Node Package Manager (NPM).

Uploaded by

Adarsh Yograaj
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

NodeJS Modules

[Link], an open-source, cross-platform JavaScript runtime environment, has revolutionized


server-side programming by providing a robust framework for building scalable network
applications. One of the key features of [Link] is its modular architecture, which allows
developers to organize their code into manageable, reusable pieces called modules.

Types of Modules in Node JS is a set of functions that can be included in your program. Node JS
has its own set of modules that can be included without installation. Every module has its own
context so it cannot be mixed with another module. Each module can be placed in a separate js
file. Consider modules to be the same as JavaScript libraries, a set of functions you want to include
in your application.

Types of NodeJS Modules:

Node js has the following 3 types of modules:

• Core modules

• Local Modules

• Third-Party Modules

• [Link] Core Modules


• [Link] is a light weight framework. The core modules include bare minimum
functionalities of [Link]. These core modules are compiled into its binary
distribution and load automatically when [Link] process starts. However, you
need to import the core module first in order to use it in your application.
• The following table lists some of the important core modules in [Link].

Core Module Description


http http module includes classes, methods and events to create [Link] http server.
url url module includes methods for URL resolution and parsing.
querystring querystring module includes methods to deal with query string.
path path module includes methods to deal with file paths.
fs fs module includes classes, methods, and events to work with file I/O.
util util module includes utility functions useful for programmers.

• Loading Core Modules


• In order to use [Link] core or NPM modules, you first need to import it using require()
function as shown below.
• var module = require('module_name');
• As per above syntax, specify the module name in the require() function. The require()
function will return an object, function, property or any other JavaScript type,
depending on what the specified module returns.
• The following example demonstrates how to use [Link] http module to create a web
server.
• Example: Load and Use Core http Module

var http = require('http');

var server = [Link](function(req, res){

//write code here

});

[Link](5000);

• In the above example, require() function returns an object because http module
returns its functionality as an object, you can then use its properties and methods
using dot notation e.g. [Link]().
• In this way, you can load and use [Link] core modules in your application. We
will be using core modules throughout these tutorials.

[Link] Local Module


• Local modules are modules created locally in your [Link] application. These
modules include different functionalities of your application in separate files
and folders. You can also package it and distribute it via NPM, so that [Link]
community can use it. For example, if you need to connect to MongoDB and
fetch data then you can create a module for it, which can be reused in your
application.

• Writing Simple Module


• Let's write simple logging module which logs the information, warning or error
to the console.
• In [Link], module should be placed in a separate JavaScript file. So, create a
[Link] file and write the following code in it.
• [Link]

var log = {
info: function (info) {
[Link]('Info: ' + info);
},
warning:function (warning) {
[Link]('Warning: ' + warning);
},
error:function (error) {
[Link]('Error: ' + error);
}
};

[Link] = log
• In the above example of logging module, we have created an object with three
functions - info(), warning() and error(). At the end, we have assigned this object
to [Link]. The [Link] in the above example exposes a log
object as a module.
• The [Link] is a special object which is included in every JS file in the
[Link] application by default. Use [Link] or exports to expose a
function, object or variable as a module in [Link].
• Now, let's see how to use the above logging module in our application.

• Loading Local Module


• To use local modules in your application, you need to load it using require()
function in the same way as core module. However, you need to specify the path
of JavaScript file of the module.
• The following example demonstrates how to use the above logging module
contained in [Link].
• [Link]
var myLogModule = require('./[Link]');

[Link]('[Link] started');
• In the above example, [Link] is using log module. First, it loads the logging
module using require() function and specified path where logging module is
stored. Logging module is contained in [Link] file in the root folder. So, we have
specified the path './[Link]' in the require() function. The '.' denotes a root folder.
• The require() function returns a log object because logging module exposes an
object in [Link] using [Link]. So now you can use logging module as
an object and call any of its function using dot notation e.g [Link]()
or [Link]() or [Link]()
• Run the above example using command prompt (in Windows) as shown below.

• C:\> node [Link]

Info: [Link] started


Export Module in [Link]
Here, you will learn how to expose different types as a module using [Link].

The [Link] is a special object which is included in every JavaScript file in the
[Link] application by default. The module is a variable that represents the current
module, and exports is an object that will be exposed as a module. So, whatever you
assign to [Link] will be exposed as a module.

Let's see how to expose different types as a module using [Link] .

Export Literals
As mentioned above, exports is an object. So it exposes whatever you assigned to it as
a module. For example, if you assign a string literal then it will expose that string literal
as a module.

The following example exposes simple string message as a module in [Link].

[Link]

[Link] = 'Hello world';

Now, import this message module and use it as shown below.

[Link]
Copy
var msg = require('./[Link]');

[Link](msg);

Run the above example and see the result, as shown below.

C:\> node [Link]

Hello World

Note:
You must specify ./ as a path of root folder to import a local module. However, you do not need
to specify the path to import [Link] core modules or NPM modules in the require() function.
Export Object
The exports is an object. So, you can attach properties or methods to it. The following
example exposes an object with a string property in [Link] file.

[Link]

[Link] = 'Hello world';

//or

[Link] = 'Hello world';

In the above example, we have attached a property SimpleMessage to the exports object.
Now, import and use this module, as shown below.

[Link]

var msg = require('./[Link]');

[Link]([Link]);

In the above example, the require() function will return an object { SimpleMessage :
'Hello World'} and assign it to the msg variable. So, now you can
use [Link] .

Run the above example by writing node [Link] in the command prompt and see the
output as shown below.

C:\> node [Link]

Hello World

In the same way as above, you can expose an object with function. The following
example exposes an object with the log function as a module.

[Link]

[Link] = function (msg) {


[Link](msg);
};
The above module will expose an object- log : function(msg){ [Link](msg); } . Use
the above module as shown below.

[Link]

var msg = require('./[Link]');

[Link]('Hello World');

Run and see the output in command prompt as shown below.

C:\> node [Link]

Hello World

You can also attach an object to [Link] , as shown below.

[Link]

[Link] = {
firstName: 'James',
lastName: 'Bond'
}
[Link]

var person = require('./[Link]');


[Link]([Link] + ' ' + [Link]);

Run the above example and see the result, as shown below.

C:\> node [Link]

James Bond

Export Function
You can attach an anonymous function to exports object as shown below.

[Link]
[Link] = function (msg) {
[Link](msg);
};

Now, you can use the above module, as shown below.

[Link]
Copy
var msg = require('./[Link]');

msg('Hello World');

The msg variable becomes a function expression in the above example. So, you can
invoke the function using parenthesis (). Run the above example and see the output as
shown below.

C:\> node [Link]

Hello World

Export Function as a Class


In JavaScript, a function can be treated like a class. The following example exposes a
function that can be used like a class.

[Link]
Copy
[Link] = function (firstName, lastName) {
[Link] = firstName;
[Link] = lastName;
[Link] = function () {
return [Link] + ' ' + [Link];
}
}

The above module can be used, as shown below.

[Link]
Copy
var person = require('./[Link]');
var person1 = new person('James', 'Bond');

[Link]([Link]());

As you can see, we have created a person object using the new keyword. Run the above
example, as shown below.

C:\> node [Link]

James Bond

In this way, you can export and import a local module created in a separate file under
root folder.

[Link] also allows you to create modules in sub folders. Let's see how to load module
from sub folders.

Load Module from the Separate Folder


Use the full path of a module file where you have exported it using [Link] . For
example, if the log module in the [Link] is stored under the utility folder under the root
folder of your application, then import it, as shown below.

[Link]

var log = require('./utility/[Link]');

In the above example, . is for the root folder, and then specify the exact path of your
module file. [Link] also allows us to specify the path to the folder without specifying
the file name. For example, you can specify only the utility folder without
specifying [Link], as shown below.

[Link]

var log = require('./utility');

In the above example, [Link] will search for a package definition file
called [Link] inside the utility folder. This is because Node assumes that this
folder is a package and will try to look for a package definition. The [Link] file
should be in a module directory. The [Link] under utility folder specifies the file
name using the main key, as shown below.
./utility/[Link]
Copy
{
"name" : "log",
"main" : "./[Link]"
}

Now, [Link] will find the [Link] file using the main entry in [Link] and import it.

If the [Link] file does not exist, then it will look for [Link] file as a module file by
default.

NPM - Node Package Manager


Node Package Manager (NPM) is a command line tool that installs, updates or
uninstalls [Link] packages in your application. It is also an online repository for open-
source [Link] packages. The node community around the world creates useful
modules and publishes them as packages in this repository.

It has now become a popular package manager for other open-source JavaScript frameworks
like AngularJS, jQuery, Gulp, Bower etc.

NPM is included with [Link] installation. After you install [Link], verify NPM
installation by writing the following command in terminal or command prompt.

C:\> npm -v

2.11.3

If you have an older version of NPM then you can update it to the latest version using
the following command.

C:\> npm install npm -g

To access NPM help, write npm help in the command prompt or terminal window.

C:\> npm help


NPM performs the operation in two modes: global and local. In the global mode, NPM
performs operations which affect all the [Link] applications on the computer whereas
in the local mode, NPM performs operations for the particular local directory which
affects an application in that directory only.

Install Package Locally


Use the following command to install any third party module in your local [Link]
project folder.

C:\>npm install <package name>

For example, the following command will install ExpressJS into MyNodeProj folder.

C:\MyNodeProj> npm install express

All the modules installed using NPM are installed under node_modules folder. The
above command will create ExpressJS folder under node_modules folder in the root
folder of your project and install [Link] there.

Add Dependency into [Link]


Use --save at the end of the install command to add dependency entry into [Link]
of your application.

For example, the following command will install ExpressJS in your application and
also adds dependency entry into the [Link].

C:\MyNodeProj> npm install express --save

The [Link] of NodejsConsoleApp project will look something like below.

[Link]

{
"name": "NodejsConsoleApp",
"version": "0.0.0",
"description": "NodejsConsoleApp",
"main": "[Link]",
"author": {
"name": "Dev",
"email": ""
},
"dependencies": {
"express": "^4.13.3"
}
}

Install Package Globally


NPM can also install packages globally so that all the [Link]
application on that computer can import and use the installed
packages. NPM installs global packages
into /<User>/local/lib/node_modules folder.

Apply -g in the install command to install package globally. For


example, the following command will install ExpressJS globally.

C:\MyNodeProj> npm install -g express

Update Package
To update the package installed locally in your [Link] project,
navigate the command prompt or terminal window path to the project
folder and write the following update command.

C:\MyNodeProj> npm update <package name>

The following command will update the existing ExpressJS module to


the latest version.

C:\MyNodeProj> npm update express


Uninstall Packages
Use the following command to remove a local package from your
project.

C:\>npm uninstall <package name>

The following command will uninstall ExpressJS from the application.

C:\MyNodeProj> npm uninstall express

You might also like