Nodejs Modules – Types and Examples

FREE Online Courses: Click for Success, Learn for Free - Start Now!

Modules are encapsulated code blocks that communicate with an external application. These can be a single file or a collection of multiple files/folders. These are reusable, hence they are widely used. Let us learn about Nodejs Modules.

Types of Modules in Nodejs:

There are three types of modules
1) Core Modules
2) local Modules
3) Third-party Modules

1. Nodejs Core Modules:

Built-in modules of node.js that are part of nodejs and come with the Node.js installation process are known as core modules.

To load/include this module in our program, we use the require function.

let  module = require('module_name')

The return type of require() function depends on what the particular module returns.

Http, file system and url modules are some of the core modules. We will be discussing this in the latter part of this blog.

2. Nodejs Local Modules:

Local modules are created by us locally in our Node.js application. These modules are included in our program in the same way as we include the built in module.

Let’s build a module with the name as sum to add two numbers and include them in our index.js file to use them.

Code for creating local modules and exporting:

exports.add=function(n,m){
    return n+m;
};

Exports keyword is used to make properties and methods available outside the file.

In order to include the add function in our index.js file we use the require function.

Code for including local modules:

let sum = require('./sum')
 
console.log("Sum of 10 and 20 is ", sum.add(10, 20))

Add the above code in a index.js file

To run this file, open a terminal in the project directory and type node index.js and press enter. You can see the result of addition of 10 and 20. This addition has been performed by the add function in the sum module.

 

3. Nodejs Third Party Modules:

Modules that are available online and are installed using the npm are called third party modules. Examples of third party modules are express, mongoose, etc.

To install third party modules refer to the previous blog where we have discussed how to install modules using npm.

Nodejs HTTP Module:

It is a built-in module of node.js. It allows node.js applications to transfer data using HyperText Transfer Protocol (HTTP).

This module creates an HTTP server that listens to server ports and also gives responses back to the client.

Properties:

1. http.METHODS: this tells us all the methods available in http module.

Code to check HTTP methods:

let http = require('http');
console.log(http.METHODS)

Output:

nodejs http methods

2. http.STATUS_CODES: It tells us all the status codes and its description.

Code to check HTTP status codes:

let http = require('http');
console.log(http.STATUS_CODES)

Output:

nodejs http status code

METHODS:

CREATE SERVER: We can use it to create a server. The create server will take a function which will run when we try to access the port.

listen() starts the HTTP server and listens for connections.

Below code sets up a server which we can access when we visit localhost:3000

Code for creating http server:

let http = require('http');
http.createServer(function (req, res) {
    res.write('Welcome to DataFlair!');
    res.end();
}).listen(3000);

Now visit localhost:3000, you will see the message

nodejs http output

Adding HTTP header:

If the message from the server needs to be shown as an HTML, then we have to include content type in the header.

Code for adding http header:

var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.write('Hello from DataFlair!');
    res.end();
}).listen(3000);

Reading query string:

The function in the create server has a request argument and this request object has a property of URL. It contains the part of the url that is present after the domain name.

So when you go to localhost:3000/dataflair/nodejs, the output will be dataflair/nodejs

Code for reading query string:

var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.write(req.url);
    res.end();
}).listen(3000);

Nodejs URL Module:

This is a built-in module of node.js. It breaks down the url into readable parts. It is included in the file by using the require function;

To Parse an address, use the url.parse() method. It will return a URL object with each part of the address as its properties.

Code for using the url Module:

let url = require('url');
var adr = 'http://localhost:3000/search?year=2021&month=august';
var q = url.parse(adr, true);
 
console.log(q.host);
console.log(q.pathname);
console.log(q.search);
 
var qdata = q.query;
console.log(qdata.month);

OUTPUT

nodejs url module

In the above image you can see that the url has been parsed and individual parts are shown in the console.

File Server:

Now we will be parsing the url and based on it we will be returning the content of the requested file. If the file is not found we will get an 404 error message. So first create a html/text file and add some content. We have made a text file with name as “DataFlair.txt” and it contains the line “Welcome to DataFlair” .

Code for serving a file over http:

var http = require('http');
var url = require('url');
var fs = require('fs');
 
http.createServer(function (req, res) {
    var q = url.parse(req.url, true);
    var filename = "." + q.pathname;
    fs.readFile(filename, function (err, data) {
        if (err) {
            res.writeHead(404, { 'Content-Type': 'text/html' });
            return res.end("404 Not Found");
        }
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.write(data);
        return res.end();
    });
}).listen(3000);

Now go to http://localhost:3000/DataFlair.txt you will get the contents present in the file.

Output:

nodejs file server output

Nodejs File System Module:

This is a built-in module of node.js. It helps to create, read, write, update, or delete files in our computer. It is included in the file by using the require function.

Create File: It has mainly 3 methods

1. Append file.

The fs.appendFile() method’s second argument takes the text that we want to append, and then it appends at the end of the file, if the given file does not exist then the file will be created.

Code for appending text in a file:

var fs=require(‘fs’)
fs.appendFile('DataFlairDemo.txt', 'welcome to DataFlair', function (err) {
    if (err) throw err;
    console.log('Saved!');
});

OUTPUT

nodejs fs append file

2. Open file

The fs.open() method’s second argument is “w” for “writing”,which indicates that the file is opened for writing and if it does not exist then an empty file is created.

Code for opening a file:

var fs=require(‘fs’)
fs.open('DataFlairDemo.txt', 'w', function (err, file) {
    if (err) throw err;
    console.log('Saved!');
});

OUTPUT

nodejs fs open file

You can see that a file has been added.

3. WriteFile:

The fs.writeFile() method’s second argument takes the text that we want to write, and then it overrides the content available in the file if the given file does not exist then the file will be created.

Code for writing in a file:

var fs = require('fs');
fs.writeFile('DataFlairDemo.txt', 'Learn Node.js from DataFlair', function (err, file) {
    if (err) throw err;
    console.log('Saved!');
});

OUTPUT

nodejs fs write file

Update File: It has mainly 2 methods

1) fs.appendFile()

The fs.appendFile() method’s second argument takes the text that we want to append, and then it appends at the end of the file, if the given file does not exist then the file will be created.

Code for fs.appendFile()

var fs=require(‘fs’)
fs.appendFile('DataFlairDemo.txt', 'welcome to DataFlair', function (err) {
    if (err) throw err;
    console.log('Saved!');
});

Output

nodejs fs append file

2) fs.writeFile():

The fs.writeFile() method’s second argument takes the text that we want to write, and then it overrides the content available in the file, if the given file does not exist then the file will be created.

Code for writing in a file:

var fs = require('fs');
fs.writeFile('DataFlairDemo.txt', 'Learn Node.js from DataFlair', function (err, file) {
    if (err) throw err;
    console.log('Saved!');
});

OUTPUT

nodejs fs write file

Read File:

It is used to read files present in your system.

Code for reading a file:

var fs = require('fs');
fs.readFile('DataFlairDemo.txt', function (err, file) {
    if (err) throw err;
    console.log('Saved!');
});

Delete File: to delete a file use fs.unlink();

Code for deleting a file:

var fs = require('fs');
fs.unlink('DataFlairDemo.txt', function (err, file) {
    if (err) throw err;
    console.log('Saved!');
});

You can see that the file is no longer visible.

nodejs fs delete file

Rename File:

If we want to rename a file we will use the fs.rename() method of the file system module.

Code for renaming a file:

var fs = require('fs');
fs.rename('DataFlair1.txt', 'DataFlair2.txt', function (err, file) {
    if (err) throw err;
    console.log('Saved!');
});

Important nodejs modules and their uses:

1. Http: Used for creating an HTTP server in nodejs.

2. Assert: Used for testing node js application using a set of assertion functions.

3. Fs: Used in modification of files.

4. Path: It helps to find the file paths.

5. Process: Gives information regarding the current process.

6. Os: It contains the details of the operating system in which the node js application is currently running.

7. Querystring: It helps in parsing and proper formatting of the url.

8. Url: This module also helps in parsing the urls.

Conclusion:

In this blog we discussed what are modules, its types, uses, and also seen the Http, url and fs modules. Hope you loved reading it and don’t forget to check DataFlair’s other blogs.

If you are Happy with DataFlair, do not forget to make us happy with your positive feedback on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *