module.exports
is a special object in Node.js that is used to expose objects, functions, or variables to the module system. It allows you to reuse code in your application by breaking it down into smaller, modular units called “modules”.
To use module.exports
, you can assign the object, function, or variable that you want to expose to it. For example:
module.exports = {
foo: 'bar',
add: (a, b) => a + b
};
In this example, the module.exports
object is being used to expose an object with two properties: foo
and add
. The foo
property is a string, and the add
property is a function that adds two numbers.
To use a module in another file, you can use the require
function and assign the result to a variable. For example:
const myModule = require('./myModule');
console.log(myModule.foo); // 'bar'
console.log(myModule.add(1, 2)); // 3
In this example, the myModule
variable is assigned the value of the module.exports
object from the myModule
file. You can then access the properties of the object using dot notation.
Keep in mind that module.exports
can only be assigned a single value, so if you want to expose multiple objects, functions, or variables, you can either wrap them in an object or use multiple module.exports
statements.