Node.js Modules

Introduction

Modules in Node.js represent a set of functions that one can include in a program to achieve specific functionalities. Modules are encapsulated code blocks that interface with an external application based on their relevant capabilities.

There are three types of modules in Node.js:

 

  1. Core modules - Node.js comes with a set of built-in modules. These modules have predefined functions to perform specific tasks.
  2. Local modules - These modules are available only locally and are created by the programmer.
  3. Third-party modules - Third-party modules can be installed via the Node Package Manager(NPM). Mongoose, express, angular, and react are some of the most popular third-party modules.

 

In this article, we'll go through how to use built-in modules in Node.js in depth. The table below lists some of the most-used core modules in node.js with their functionalities.

 

Core Modules

Functionality

http

Includes classes, methods, and events to create Node.js HTTP server.

path

Includes methods to handle file paths.

querystring

Includes utility functions to parse/format URL strings.

fs

Includes methods to handle I/O.

url

Used for URL resolution and parsing.

os

Includes functions to get info about the operating system.

 

Loading Core Modules

 

To use Node.js core modules, you must first import them using the required function, as demonstrated below.

 

var modulerequire('module_name');

 

In the require method, use the syntax above to specify the module name. The required () method will return an object, function, property, or other JavaScript types depending on what the supplied module returns. For example - 

 

var module_http = require('http');

 

In the above example, module_http is a JS object as the HTTP module returns its functionality as an object. You can now access the methods and properties defined in the HTTP module via this object module_http.

 

Create Your Own Modules

 

You can create your own modules and include them in your Node.js applications. Let us create a simple module that contains methods to do various operations. Create a file named module.js and edit it to contain the following - 

 

// Custom module definition
exports.add = function (a, b) {
  return a + b; // Add the numbers.
};

exports.sub = function (a, b) {
  return a - b; // Subtract the numbers.
};

exports.mul = function (a, b) {
  return a * b; // Multiply the numbers.
};

exports.divfunction (a, b) {
  return a / b; // Divide the numbers.
};

 

Now create another file named index.js and import the module defined in the previous file - 

 

// Import the module using the following statement.
var calc= require('./module');

var a = 1210

console.log("a + b = " + calc.add(a, b));

console.log("a - b = " + calc.sub(a, b));

console.log("a * b = " + calc.mul(a, b));

console.log("a / b = " + calc.div(a, b));

 

Output - 

 

 

Usage of Core Modules

HTTP Module

 

There is a built-in module HTTP in Node.js for making HTTP queries and transferring data over HTTP. The HTTP module is required to use/create the HTTP server in Node. The HTTP module defines methods to create an HTTP server that listens to server ports and responds to client requests.

 

const http = require('http');

const port = 3000;

const server = http.createServer((req, res) => {
  console.log(req.url);
  req.statusCode = 200;
  res.setHeader('Content-Type''text/html');
  res.end('<h1>The response is coming from Node.js HTTP server.</h1>');
})

server.listen(port, () => {
  console.log("Server is listening...");
})

 

Output - 

 

 

Now visit localhost:3000 to see the server response.

FS Module

 

Node.js has an inbuilt module called FS that handles file operations, including creating, reading, and deleting files. All file system operations might be synchronous (blocking) or asynchronous (non-blocking), depending on the user's needs.

 

Let us go through some of the functions defined in the fs module.

 

Reading File

 

Use readFile() method to read the physical file asynchronously. Create a file named fsmodule.js and write the following code into it - 

 

var fs = require('fs');

fs.readFile('myfile.txt'function (err, data) {
  console.log(err); // error is printed as well if there is an error.
  console.log(data.toString()); // data is printed after converting to string.
});

console.log("This is executed asynchronously."// this statement will be executed in parallel (asynchronously).

 

 

In the above example, the readFile function executes asynchronously. So, while the file is read, the following statements are executed as well.

 

Now let us consider the function readFileSync, which reads the file synchronously.

Create a file named fsmodulesync.js and write the following code into it - 

 

var fs = require('fs');

var data = fs.readFileSync('myfile.txt''utf8'); // All the following statements will be executed only after file reading is complete.
console.log(data);

console.log("This is executed synchronously."// this statement will be executed in parallel (synchronously).

 

 

As it is clear, the statements following the readFileSync method call execute only when file reading is completed. In a similar way, functions writeFile and writeFileSync perform write operations asynchronously and synchronously respectively.

OS Module

The OS module in node.js is primarily used for getting information about the operating system installed in your system. Various functions are defined in the OS module that provides information like free memory left in the system, current home directory, hostname, etc. Notice the difference in the way we import a local module and a built-in module.

 

Create a file named osmodule.js and paste the following code into it.

var osmodule = require('os')

console.log(osmodule.freemem()) // calculates the free memory left.
console.log(osmodule.homedir()) // returns the current home directory     (not working directory).
console.log(osmodule.hostname()) // returns the hostname.
console.log(osmodule.release()) // returns the release version of your operating system.
console.log(osmodule.platform()) // returns the name of the operating     system.

 

Output - 

Frequently asked Questions

Q1. What is a module in Node.js?

 

Ans: Modules are wrapped code units that interface with an external application based on their relevant functionality in Node. js. Modules might consist of a single file or a collection of files/folders.

 

Q2. How do modules work?

 

Ans: Node. js modules serve as building blocks for code structure, allowing developers to better structure, reuse, and distribute code. A module is a self-contained file or directory of related code that may be included wherever needed in your program.

 

Q3. What do modules contain?

 

Ans: Modules contain classes, methods, and events meant for specific purposes. For example, the http module contains createServer method that creates a Node.js server.

 

Q4. How do I import a node.js module?

 

Ans: To import a local module using the following syntax - 

var local_module = require('./local_module');

To import a built-in or third-party module, use the following - 

var modulerequire('module_name');

 

Key Takeaways

In this blog, we learned about Node.js modules. We learned that Node.js modules are of three types - Built-in, local, and third-party. 

Then we learned how to create local modules and use them. We looked at the way local modules and built-in modules are imported. 

Then we had a glimpse of how to use Node.js built-in modules. The HTTP Module contains methods to create and manage Node HTTP servers. The FS module has functions that handle file operations. Details about other modules can be found here - Modules: CommonJS modules.


Aman Chourasiya

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think