Modular Programming in Node.js

6 min read

A beginner’s guide on Modular Programming in Node.js

Modules are one of the fundamental features of the latest technology that any Node.js development company focuses on. Whenever you are building an application, the code becomes larger with an increase in features and might become complex. It is not a good habit or standard to put your all code in a single file. keeping your all code inside a single file becomes very hard to manage, to resolve this issue the modular approach is the best use case.

In JavaScript frameworks or libraries, modular programming becomes more efficient as the developer can write code in different files export the code using methods, and export functions to the required file.

What is a module?

Node.js Introduction - GeeksforGeeks

Modules are the block of code that is separated. It communicates with the external files or applications according to the functionality. In JavaScript, a single file containing a single or specific functionality can also be counted as a module.

In node, we can import or export our own created files, core node modules, and NPM modules as modules.

How to import own Created files

Let’s say we have created two files for the demo one is a module.js file and the other is index.js. For simplicity, both the files are in the same directory.

Modular Programming in Node.js

Fig – 1.1 import Files

Now, to import something in the index.js file you have to export that from the module.js file.

To import function() :

Modular Programming in Node.js

Fig – 1.2 import function in node

Whenever a function or object or variable needs to be exported in node.js it is exported using the module.exports syntax.

Node.js treats each file as one module and this exports is a property of the module object.

//index.js

const add = (a, b) => {

return a + b;

};

module.exports = add;

Exporting and importing Class :

//person.js

// constructor function for the class Person

const Add = class {

constructor(a, b) {

this.a = a;

this.b = b;

}

result() {

return this.a + this.b;

}

};

module.exports = Add;

In this, the person.js file Class named PersonDetail contains Objects name such as name and age. This class is exported using module.exports. To use this class we have to import this person.js file into the index file.

//index.js

const add = require(“./calculate”);

const result = new add(2, 5);

console.log(result.result());

To create the instance of class PersonDetail in the index.js file we use a new keyword.

Import an Object:

We can export an entire object as well and can access the variable and methods as well.

//module.js

const addNum = {

result: (a, b) => {

return a + b;

},

};

module.exports = addNum;

Now, we can import this object inside the index.js file using require() method.

And we can also access the sum() method inside the addNum object using the (.)dot operator.

const addNum = require(‘./module’);

const result = addNum.sum(5, 8);

console.log(result);

We can directly export the sum() method inside the addNum object and then we import only that method using require() function.

//calculate.js

const addNum = {

sum: (a, b) => {

return a + b;

},

};

module.exports = addNum.sum;

//index.js

const add = require(‘./calculate’);

const result = add(5, 8);

console.log(result);

This is good coding practice because sometimes you don’t need an entire object but only need some of the methods or functions of that object.

Related Post  Make Your Website More Visually Appealing

Import Core Node Modules:

Node provides a set of modules that provides some of the functionality so we do not need to create a custom module every time. Importing these modules is similar to how we import custom modules in files. We use the same require() method to import the module.

But there are some modules we do not need to import using require() method because they are globally available. for example, the console is the module we use so many times but we do not import that into our files.

These are the some of the Node’s core modules:

• http

• url

• fs

• os

• path

• utils

There is one core module available is fs module(file System). we can perform so many operations with the fs module. We can read, update, and write files using the fs module. We can read files two ways using the fs module. One is the synchronous way fs.readFileSync() and the other is the asynchronous way using fs.readFile().

To read the file using the fs module there has to be one file that can be read.

Modular Programming in Node.js

Now we can import the fs module into our file and use the fs module to read the file.

const fs = require(‘fs’);

fs.readFile(‘./file.txt’, ‘utf-8’, (err, data) => {

if (err) throw err;

console.log(data);

});

Node.js NPM module :

NPM stands for the node package manager.

To import any package from NPM, first, we need to initialize NPM on the local system by using the command “ npm init -y”

Once you fire that command it will create one package.json file in your project. that file has information regarding your packages, version, and dependencies. which will look something like this.

{

“name”: “node_demo”,

“version”: “1.0.0”,

“description”: “”,

“main”: “index.js”,

“scripts”: {

“test”: “echo \”Error: no test specified\” && exit 1″

},

“keywords”: [],

“author”: “”,

“license”: “ISC”

}

You can install that package into your project using the node command “npm install package_name” After installing the project you can import that package into your file just by using require() function.

For example, The moment is an npm package that is used to display and format dates in Node.js. To use that package in the project we first need to install that using “npm install moment”.

And then to use that package in a particular file we need to import the package using require().

//index.js

const moment = require(‘moment’);

const currentDate = moment();

console.log(

‘The date today is ‘ + currentDate.format(‘dddd, MMMM Do YYYY, h:mm:ss a’)

);

Conclusion

Node modular programming allows us to export our own files, objects, functions and classes. We can also import core modules of the node.js what we need to use them is to import them with the help of require() function.

We can also import third-party packages that can be used after installing them the rest of the implementation is the same as the core modules and our own files. Modular programming helps to keep code reusability, making it secure, and making it secure and making it secure and allowing us to use the advantage of encapsulation.

Related Post  Sans Serif vs Serif Font

Author Bio: Vinod Satapara – Technical Director, iFour Technolab Pvt. Ltd.

Technocrat and entrepreneur of a reputed Angular Development Company with years of experience building large-scale enterprise web, cloud, and mobile applications using the latest technologies like ASP.NET, CORE, .NET MVC, Angular, and Blockchain. Keen interest in addressing business problems using the latest technologies and helping organizations to achieve goals.

LinkedIn: https://www.linkedin.com/in/vinodsatapara/

Leave a Reply

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

CommentLuv badge