Exposing Functionality from a Node File Using exports
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:
1 | 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:
1 | const car = { |
- Add the exported object as a property of
exports
. This method allows you to export multiple objects, functions, or data:
1 | const car = { |
Alternatively, you can directly export the object:
1 | exports.car = { |
In the other file, you can use the imported functionality by accessing the respective property:
1 | const items = require('./items'); |
Or, you can destructure the imported functionality directly:
1 | 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.
tags: [“Node.js”, “module.exports”, “exports”, “functionality”, “importing”]