Node Export Module

In Node, the `module.exports` is utilized to expose literals, functions, or objects as modules. This mechanism enables the inclusion of JavaScript files within Node.js applications. The `module` serves as a reference to the current module, and `exports` is an object that is made accessible as the module’s public interface.

Syntax:

module.exports = literal | function | object

Note: Here the assigned value (literal | function | object) is directly exposed as a module and can be used directly.

Syntax:

module.exports.variable = literal | function | object

Note: The assigned value (literal | function | object) is indirectly exposed as a module and can be consumed using the variable.

Below are different ways to export modules:

Table of Content

  • Exporting Literals
  • Exporting Object:
  • Exporting Function
  • Exporting function as a class

Example 1: Exporting Literals

Create a file named as app.js and export the literal using module.exports.

module.exports = "w3wiki"; 

Create a file named as index.js and import the file app.js to print the exported literal to the console.

const company = require("./app"); 
console.log(company);

Output:

w3wiki

Example 2: Exporting Object:

Create a file named as app.js and export the object using module.exports.

module.exports = { 
name: 'w3wiki',
website: 'https://w3wiki.net'
}

Create a file named as index.js and import the file app.js to print the exported object data to the console.

const company = require('./app'); 
console.log(company.name);
console.log(company.website);

Output:

w3wiki
https://w3wiki.net

Example 3: Exporting Function

Create a file named as app.js and export the function using module.exports.

module.exports = function (a, b) { 
console.log(a + b);
}

Create a file named as index.js and import the file app.js to use the exported function.

const sum = require('./app'); 
sum(2, 5);

Output:

7

Example 4: Exporting function as a class

Create a file named as app.js. Define a function using this keyword and export the function using module.exports and Create a file named index.js and import the file app.js to use the exported function as a class.

Javascript




const Company = require('./app');
const firstCompany = new Company();
firstCompany.info();


Javascript




module.exports = function () {
    this.name = 'w3wiki';
    this.website = 'https://w3wiki.net';
    this.info = () => {
        console.log(`Company name - ${this.name}`);
        console.log(`Website - ${this.website}`);
    }
}


Output:

Company name - w3wiki
Website - https://w3wiki.net