The module.exports in Node.js is used to export any literal, function or object as a module. It is used to include JavaScript file into node.js applications. The module is similar to variable that is used to represent the current module and exports is an object that is exposed as a module.
Syntax:
-
module.exports = literal | function | object
Explanation: Here the assigned value (literal | function | object) is directly exposed as a module and can be used directly.
-
module.exports.variable = literal | function | object
Explanation: Here the assigned value (literal | function | object) is indirectly exposed as a module and can be consumed using the variable.
Example 1: Exporting Literals
- Create a file named as app.js and export the literal using
module.exports
.
module.exports = "GeeksforGeeks" ;
|
- 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:
GeeksforGeeks
Example 2: Exporting Object
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
Example 5: Load Module from Separate Folders
const index = require( './models/lang/index.js' );
|
Explanation: In the above example, the index.js file is under lang folder that is inside models folder. We can use the ./
to go to the root folder then we move relative to it.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
12 Oct, 2021
Like Article
Save Article