Importing and exporting modules in Node.js

  • Post category:Node
  • Reading time:2 mins read

Now, let’s look at some examples of importing and exporting modules in Node.js, and then I will explain the code. s

Importing and exporting modules in Node

Folder Structure:

importing and exporting node modules

Code:

//Calculations.js

// module.exports
const C = require("./Module1");
const calc1 = new C();
console.log(calc1.add(2, 5));

// exports
const { add, multiply } = require("./Module2");
console.log(add(2, 5));
console.log(multiply(2, 5));

// caching
require("./Module3")();
require("./Module3")();
require("./Module3")();
//Module1.js

module.exports = class {
  add(a, b) {
    return a + b;
  }

  multiply(a, b) {
    return a * b;
  }

  divide(a, b) {
    return a / b;
  }
};
//Module2.js

exports.add = (a, b) => a + b;
exports.multiply = (a, b) => a * b;
exports.divide = (a, b) => a / b;
//Module3.js

console.log("Module3");
module.exports = () => console.log("Module3 exported");

Output:

importing and exporting in node

Code Explanation

I have imported module1.js, module2.js, and module3.js in Calculations.js. On line number 5, new C() creates an instance of that class. On line number 6, This line calls the add method on the calc1 instance, passing 2 and 5 as arguments.

In module1.js, I have exported a class and in that i have different functions such as add, multiply, and divide.

In module2.js, I have directly exported the function.

In module3.js, I used console.log() at two places. Now, whenever, I call require(“./Module3”)(); in Calculations.js then it will give the below output.

Module3
Module3 exported
Module3 exported
Module3 exported

In this, you can see that module3 is printed only one times and that’s because of the caching. The second and third require(“./Module3”) calls do not log “Module3” again (due to module caching) but log “Module3 exported” when the cached function is called.

Share this