Modules and Require

Modules

Node.js implments a module system based in CommonJs specifications. A module is a block of reusable code which does not affect or impact accidentally any other written code which means that you can break your app into small manageabable chunks. So an app can be distributed into multiple modules using each others for a better coding and maintenance.

Each module has it's own scope, varibales, methods so that each module will not interfere with the scope of other modules. Node.js allow this separate of code using IIFE (immediatly invoked function expressions) which means whenever you call a module, this module will be wrapped in an IIFE function that takes as parameters: exports, require, module, __filename__, __dirname__ and return the module.exports attribut.

Types of modules

  • Core or native modules: The build-in modules provided by Node.js (Example: http module used before).
  • External modules: our own developped modules or 3rd libraries.

Building our first small module

A module is just a piece of code written inside ".js" files to be used by other modules. In this example we will create a module named Calcul which will handle for example the sum of two numbers.

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

const mul = (a, b) => {
    return a * b;
}


const calcul = {
    mul,
    sum
}

module.exports = calcul

module.exports: is a special variable (which has an empty object as value) provided by Node.js to make our code available outside of our module in order to be used by other modules.

exports and module.exports point to the same object reference so unless the reference is changed you can use either module.exports or exports.

Using our module

In order to use this module, we will use a function that is available inside of Node.js core, which is "require" that takes the location or the name of the module (You will know more in the NPM section).

const http = require("http");
const calcul = require("./calcul");
//const calcul = require("./calcul/index")
//const calcul = require("./calcul/index.js")

const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-type': 'text/html' });

    let a = 5;
    let b = 6;

    // Template Literals in ES6 in Javascript
    res.write(`<p>${a} + ${b} = ${calcul.sum(a, b)}</p>`);
    res.write(`<p>${a} * ${b} = ${calcul.mul(a, b)}</p>`);

    res.end();

}).listen(3000, () => console.log("Server listening on port 3000"));

Require

  • require: is a special variable provided by Node.js to use whatever was exported by module.exports. When requiring a file, Node.js will look for the file, or the file.js if the extension is not specified, or in case of requiring a folder, it will look for index.js inside that folder.
  • require will always start looking for core modules before looking for other modules.
  • When requiring the same module in different locations, the module will be cached and returning the same instance of the module.exports.

In this example we used Template Literals in ES6 in Javascript, you can use + instead, if you are not familiar with ES6.

Source code

The full implementation of this article can be found in the GitHub project: Node.js learning