Node.js module.exports is a special object that is used to define and export the public interface of a module. In other words, it allows you to expose functions, variables, and objects defined in a module, so that other modules can use them.
To use module.exports, you simply assign the value you want to export to module.exports. For example, if you have a module called math.js that defines a function called add, you could export it like this:
function add(a, b) {
return a + b;
}
module.exports = {
add: add
};
In this example, we define the add function and then assign it to a property of the module.exports object called add.
We could also have assigned the add function directly to module.exports like this:
module.exports = add;
In this case, we are exporting the add function itself rather than an object that contains it.
Once you have defined the public interface of your module using module.exports, you can use it in other modules by requiring the module and accessing its exported properties. For example, if you wanted to use the add function from the math.js module in another module, you would do something like this:
var math = require('./math.js');
var result = math.add(1, 2);
console.log(result); // prints 3
In this example, we are requiring the math.js module and assigning it to a variable called math. We can then access the add function using math.add and call it with two arguments to get the result.
Comments (0)