Learn how to use the module.exports
API to expose data to other files in your Node.js application or even to other applications.
Node.js comes with a built-in module system that allows files to import functionality from other files. To import something, you can use the following syntax:
const library = require('./library');
This imports the functionality that is exposed in the library.js
file located in the same folder as the current file.
In order for functionality to be imported, it must be explicitly exposed in the file. By default, any object or variable defined in the file is private and not accessible from outside. This is where the module.exports
API comes in.
The module.exports
API, provided by the module system, allows you to expose an object or a function for importing in other parts of your application or even in other applications.
There are two ways to use the module.exports
API to expose functionality:
- Assign an object directly to
module.exports
. This will export only that specific object:
const car = {
brand: 'Ford',
model: 'Fiesta'
};
module.exports = car;
// In the other file
const car = require('./car');
- Add the exported object as a property of
exports
. This method allows you to export multiple objects, functions, or data:
const car = {
brand: 'Ford',
model: 'Fiesta'
};
exports.car = car;
Alternatively, you can directly export the object:
exports.car = {
brand: 'Ford',
model: 'Fiesta'
};
In the other file, you can use the imported functionality by accessing the respective property:
const items = require('./items');
items.car;
Or, you can destructure the imported functionality directly:
const car = require('./items').car;
In summary, module.exports
exposes the object it points to, while exports
exposes the properties of the object it points to.