Simplify Your Node.js Code with Modular Design: Local, Core, and Third-Party Modules

Rahul Kumar
6 min readSep 10, 2024

--

Modules and it’s Specifications

What is modules?

  • Modules are files containing JavaScript related code that serve a specific purpose.
  • Modules can be a single file or a collection of multiple files and folders.

Why developers used modules?

→ Because of these features or advantages of using modules:

  • Reusability as well as their ability to break down complex code into manageable chunks.
  • Readability: Modular code highly organizes the program based on its functionality. This allows the developers to understand what each piece of code does in the application.
  • Easier to debug: When debugging large programs, it is difficult to detect bugs. If a program is modular, then each module is discrete, so each module can be debugged easily by the programmer.
  • Reusable Code: Modular code allows programmers to easily reuse code to implement the same functionality in a different program. If the code is not organized modularly into discrete parts, then code reusability is not possible.
  • Reliability: Modular code will be easier to read. Hence it will be easier to debug and maintain the code which ensures smoother execution with minimum errors.

What is the purpose of import() and require()?

  • When an external application needs to use the code contained in a module the application needs to call that module.
  • module is called using an import() or a require() statement.

What is package?

→ A directory with one or more modules bundled together is called a package.

What is module specifications?

→ Module specifications are the conventions and standards used to create packages in JavaScript code for Node.js applications.

  • The most commonly used module specifications for Node.js applications are CommonJS and ES modules.
  • By default, Node.js treats JavaScript code as a CommonJS module.

How to enable ES modules in Node.js?

  • By changing the package file extension from .js to .mjs.
  • By modifying the package.json file to include the following property:
"type": "module"

Importing and Exporting modules:

Difference between require() and import():

  • Modules imported with require are synchronous (It means the modules will be loaded and processed in a linear fashion, one at a time ) in nature and Modules imported with import are asynchronous (Asynchronous means the modules can be processed simultaneously ).
  • Import runs faster compared to require functions in large-scale applications which involve loading hundreds of modules.

How to import and exports using require() and import() ?

Types of Module in NodeJS:

There are three types of Modules:

  1. Local Modules
  2. Core Modules Or Inbuilt Modules
  3. Third-Party modules

Local Modules:

In Nodejs, if we want to add a set of functionality in our application, we can create it locally and use them, this locally created functionality is known as local modules.

Let’s see how to create your own modules:

  • By default the functions declared in one module are visible only in that specific module.
function add(num1, num2) {
return "Result: ", num1 + num2;
}
function substract(num1, num2) {
return "Result: ", num1 - num2;
}

function Call() {
console.log("calling");
const result = add(2, 3);
const result1 = substract(3,2);
console.log(result1)
console.log(result);
}

Call();
  • In order to export the functionalities of one module into another, Node.js has provided an object called “exports”.
  • Exports object is a built-in object of Node.js to which all the functionalities are to be attached.

How to create local modules and exports it and Imports it in other file in order to use that:

Example:

There are ways to import module in other file:

1st way:

calculator.js

// directly exports
exports.add=(a,b)=>{
return a+b
}
exports.sub=(a,b)=>{
return a-b
}
exports.mul=(a,b)=>{
return a*b
}

using these function in file index.js

const calc=require("./Calculator")
console.log(calc.add(23,45))
console.log(calc.sub(123,45))
console.log(calc.mul(12,12))

2nd way:

Calculator.js

// console.log(module.exports)     // {} 
// const add = (a,b) => a+b;
// const sub = (a,b) => a-b;
// module.exports = add;
// module.exports =sub; last one will run

// module.exports.add = add;
// module.exports.sub = sub;

// so better put as object or array
// module.exports = {add,sub}
const add=(a,b)=>{
return a+b
}
const sub=(a,b)=>{
return a-b
}
const mul=(a,b)=>{
return a*b
}
module.exports={add,sub,mul}

Use functions in another file index.js:

const {add,sub,mul}=require("./Calculator") //another way of accessing by desctructuring data
console.log(add(23,45))
console.log(sub(123,45))
console.log(mul(23,45))

There are ways to exports:

In commonJS module:

Syntax:

module.exports.functionName = function()

Example:

module.exports.greet = function(name) {
return `Hello, ${name}!`;
};

Syntax:

exports.function_name = () => {}

Example:

exports.greet = function(name) {
return `Hello, ${name}!`;
};

exports as object:

function add(num1, num2){
console.log("Result:", num1 + num2);
}

function substract(num1, num2){
console.log("Result:", num1 - num2);
}

module.exports={add, substract}

In ES6+ modules:

// module.mjs
export function greet(name) {
return `Hello, ${name}!`;
}

export default class Person {
constructor(name) {
this.name = name;
}
}

What is global modules?

In Node.js, global modules are modules that are accessible from any part of your application without requiring explicit imports. They are built-in to the Node.js environment and provide fundamental functionality.

example:

  • console: Provides methods for printing to the console (e.g., console.log, console.error).
  • process: Provides information about the current process (e.g., process.argv, process.env).
  • global: Represents the global object in Node.js, which contains properties and methods accessible from anywhere.
  • __dirname: Represents the directory name of the current module.
  • __filename: Represents the file name of the current module.

Core Modules Or Inbuilt Modules:

Node environment provides many built-in modules that can be used in application development.

  • http module, which is a built-in module in Node.js for creating a web server.
  • fs module (used for file-related operations).
  • os module(used for operating system-related functions)
  • net module( used for socket programming), etc. for server-side application development.

NPM:

Before learning third party modules, we need to learn about npm.

  • NPM is the default package manager for node.js.
  • It is one of largest software registries in the world.
  • Used for managing and sharing Javascript packages and libraries.

Most Used npm Commands:

npm init: Initializes a new Node.js project and create package.json file.

npm install package_name : Installs a package and adds it to your project’s dependencies.

npm uninstall package_name : Uninstalls a package and remove it from your project’s dependencies.

npm update : Updates all or specified packages to their latest versions.

npm publish : publish your package to npm registry.

Third-Party Modules:

Third-party modules, also known as packages, are pre-built software components that you can integrate with Node.js projects to extend their functionality and save development time.

These modules are typically published on platforms like npm (Node Package Manager) and can be installed and used with ease.

Common Use Cases for Third-Party Modules:

  • HTTP Requests: Modules like axios, request, and node-fetch simplify making HTTP requests to external APIs.
  • Database Interactions: Modules like mongoose (for MongoDB), sequelize (for various databases), and knex (for SQL databases) provide abstractions for database operations.

Q.What happens when we use require(‘path’)?

these things will happen:

1. Resolving the Module:

  • Checks for the module in the current directory.
  • If not found, searches in the node_modules directory.
  • If still not found, searches in the global module directory.

2. Loading the Module:

  • Loads the module’s code based on the file extension (e.g., .js, .json).
  • Wraps the code in a function to create a module scope.

3. Wrapping:

  • Encloses the module’s code within a function that returns an object.
  • This object becomes the module.exports object.

4. Evaluation:

  • Executes the module’s code.

5. Caching:

  • Caches the loaded module to avoid re-loading it if required again.

Thanks…

--

--

Rahul Kumar
Rahul Kumar

Written by Rahul Kumar

MERN Stack Developer building scalable web apps with MongoDB, Express.js, React, and Node.js. Sharing insights and best practices for modern web development.

No responses yet