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.
Putting all code in a single file is not a good habit or standard. Keeping all your code inside a single file becomes very hard to manage. To resolve this issue, the modular approach is the best use case.
Modular programming becomes more efficient in JavaScript frameworks or libraries 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?
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.
To import something in the index.js
file, you have to export it from the module.js
file.
Exporting Functions and Objects in Node.js
In Node.js, when you want to make a function, object, or variable available for use in other parts of your code, you can export it using the module.exports
syntax. Node.js treats each file as a module, and the exports
object is a property of the module
object, allowing you to share code between different modules.
//index.js const add = (a, b) => { return a + b; }; module.exports = add;
Exporting and importing Class
// person.js // Define a constructor function for the class Person const Add = class { constructor(a, b) { this.a = a; this.b = b; } // Define a method to calculate and return the result result() { return this.a + this.b; } }; // Export the Add class for use in other modules module.exports = Add;
In the person.js
file, there is a class named PersonDetail
that contains objects such as name
and age.
This class is exported using module.exports.
To use this class, you need to import the person.js
file into the index.js
file.
// index.js const Add = require("./calculate"); // Use a capitalized name for consistency const result = new Add(2, 5); console.log(result.result());
In the index.js
file, to create an instance of the PersonDetail
class, we use the new
keyword.
Import an Object
We can export an entire object as well and can access the variables 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 the require()
method. We can also access the result()
method inside the addNum
object using the dot operator (.).
const addNum = require('./module'); const result = addNum.result(5, 8); console.log(result);
We can export the result()
method directly inside the addNum
object, and then when importing in another file using the require()
function, we access the method by referencing it through the addNum
object.
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.
Import Core Node Modules
Node provides a set of modules that provide 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 the require()
method because they are globally available.
For example, the console is the module we use many times, but we do not import that into our files.
Some of Node.js’s core modules include:
- http
- url
- fs
- os
- path
- utils
One of the core modules available in Node.js is the fs
module, which stands for the File System module. This module enables various file operations, allowing you to read, update, and write files in your Node.js applications.
When working with the fs module in Node.js, there are two methods for reading files. You can read files synchronously using fs.readFileSync()
, or you can read them asynchronously using fs.readFile()
.
To read the file using the fs module, there has to be one file that can be read.
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 Node Package Manager. To import any package from NPM, you should first initialize NPM on your local system using the npm init -y
command.
When you run the npm init -y
command, it creates a package.json
file in your project. This package.json
file contains information about your project, including its name, version, description, main script, and other details. It typically looks 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 the require()
function.
For example, moment
is an npm package that displays and formats dates in Node.js.
To use that package in the project, we first need to install it using npm install moment
.
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 enables us to export our own files, objects, functions, and classes. We can also import core modules of Node.js by using the ‘require()’ function.
Additionally, we can import third-party packages, which are used after installation in the same way as core modules and our own files.
Modular programming promotes code reusability and encapsulation and helps ensure code security.