Node.js Module

A typical production ready Node.js application is feature intensive (the endpoints of Restful API’s are typical example where each endpoint is a feature and have a unique responsibility) and demands some amount of logic which in turn demands that you code lots of functions that are responsible for realizing the different features that make up your application. To keep our application maintainable it’s a good practice to split the different logic into smaller pieces that have specific responsibilities and then import these pieces of logic into the main application for reuse.

Module in Node.js

Module in Node.js is a simple or complex functionality organized in single or multiple JavaScript files which can be reused throughout the Node.js application. Each module in Node.js has its own context, so it cannot interfere with other modules or pollute global scope. Also, each module can be placed in a separate .js file under a separate folder.

Module Structure in Node.js

The Module System Architecture

In Node every file is considered a module and before each file (module) is executed, it’s wrapped within a Module Wrapper function which exposes the following variables/arguments module, exports, require, filename, dirname and looks something like;

(function(exports, require, module, __filename, __dirname) {
  // module code goes in here
});

The exports and module object exposed by the wrapper function enable the module to expose functions/objects to be used by other modules. the require object allows for the module to import other module(s), the __filename, __dirname are both convenience variables for accessing the file and directory path of the module respectively. It’s equally important to note that the variables exposed by the wrapper function are not globally scoped. Instead, they are locally scoped to the module and every other variable declared within the module (in the global scope of the module) are also not directly accessible by other modules when the module is imported into another module except these variable are explicitly exported by the module. Hence, object naming collision is easily avoided between the importing module and imported module.

module.exports

module.exports property exposes values from the module which can be imported into other modules by require('/path/to/module') and reused. Let’s create a utility.js module, that exposes an addition and subtraction function.

const add = (a, b) => {
  return a + b;
}

const subtract = (a, b) => {
  return a - b;
}

module.exports.add = add;
module.exports.subtract = subtract;

module.exports.add pushes the add function into the exports object assigning add as the key and the add function as the value. module.exports.subtract also assigns subtract as the second property of the exports object within the module object. To further illustrate this, let’s log the module object to the console.

require

require is a function used for loading a module into another module. It exposes the imported(the module been required) modules exported objects and makes them usable withing the requiring module.

const utility = require('./utility');

utility.add(10, 6); // returns 16
utility.substract(9, 6) // returns 3

There are are different types of module you can typically load by calling the require function;

  • Node core module e.g http, fs, net, etc
  • Application dependency module, typically loaded from node_modules
  • local module/files

When loading a core module or a module in the node_modules folder you simply reference the module name e.g; const http = require('http'), cosnt socketIo = require('scoket.io'). To load a local module(file) you need to add the file path to the module e.g const utility = require('./utility) this means the utility module is in the same directory as the module importing it.

How Module loading works

when loading a module node checks if the module identifier (the string passed into the require function call) begins with ‘./’ or ‘/’ or ‘../’ and when they don’t Node checks if the identifier matches any of it’s core module (http, net, fs, etc) and it finds a match, it loads the identified core module else Node knows to look into node_modules folder for the required module.

  • ‘./’ is a relative path to the module and it means that both modules (the imported module and the importing module) must be in the same directory
  • ‘../’ is also indicates a relative file path to the module, but this time both modules are not in the same directory level.
  • ‘/’ is an absolute path to the module, and node starts looking from the root of the file system

Node.js Module Types

Node.js includes three types of modules:
  1. Core Modules
  2. Local Modules
  3. Third Party Modules

That’s it!
You have successfully completed the post. Do Share : )

Peace Out!

Also Read – https://codingtimes.in/basics-of-nodejs/


Check Out Deals on ->Amazon , Flipkart , Myntra , Adidas , Apple TV , Boat , Canva , Beardo , Coursera , Cleartrip , Fiverr , MamaEarth , SwiggyKFC


Leave a Reply

Your email address will not be published.