nodejs module exports
In Node.js, the module.exports
object is used to define what functionality a module exports for use in other modules. When you define a module, you can assign any value or function to the module.exports
object, and that value or function can then be used by other modules that require your module.
For example, suppose you have a file called myModule.js
that defines a function that returns the square of a number:
function square(x) { return x * x; } module.exports = square;Source:www.theitroad.com
In this case, we are assigning the square
function to the module.exports
object, which means that other modules can use this function when they require myModule.js
.
To use the myModule.js
module in another file, you can use the require()
function to import the module and assign it to a variable:
const square = require('./myModule'); console.log(square(5)); // Output: 25
In this example, we import the myModule.js
module using the require()
function, and assign the square
function exported by the module to a variable. We can then call the square()
function with an argument of 5 to calculate the square of 5.
Note that you can assign any value or function to the module.exports
object, not just a single function as in the example above. For example, you could export an object with multiple properties and functions:
const myObject = { name: 'John', age: 30, greet() { console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`); } }; module.exports = myObject;
In this case, we are assigning an object with the name
, age
, and greet()
properties to the module.exports
object, which means that other modules can use this object and its properties and functions when they require this module.
const myObject = require('./myModule'); console.log(myObject.name); // Output: John console.log(myObject.age); // Output: 30 myObject.greet(); // Output: Hello, my name is John and I am 30 years old.
In this example, we import the myModule.js
module using the require()
function, and use the exported object and its properties and functions in our application.