Exporting and importing modules
In Node.js, modules are blocks of code that can be used across different files in your project. Modules can be anything from simple functions, classes, objects, or variables. To use these modules in other files, you need to export them from one file and import them into another.
1. Exporting Modules
There are two primary ways to export modules in Node.js: using module.exports and using exports.
Using module.exports
You can assign a single object, function, or variable to module.exports to make it available in other files.
// File: calculator.js
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
module.exports = {
add,
subtract
};
In this example, both add and subtract functions are being exported as properties of an object.
Using exports
The exports object is just a reference to module.exports. You can attach properties or methods to exports.
// File: calculator.js
exports.add = function(a, b) {
return a + b;
};
exports.subtract = function(a, b) {
return a - b;
};
In this approach, each function is attached to the exports object.
2. Importing Modules
To use the exported modules in another file, you can use the require() function.
// File: app.js
const calculator = require('./calculator');
console.log(calculator.add(5, 3)); // Outputs: 8
console.log(calculator.subtract(5, 3)); // Outputs: 2
Key Points to Remember:
-
module.exportsvs.exports:module.exportsallows you to export a single entity (e.g., an object, function, or class).exportsis a shortcut to attach properties or methods to themodule.exportsobject.- You can't reassign
exportsdirectly to a value (e.g.,exports = someFunction), as it will break the link betweenexportsandmodule.exports.
-
Default Export: If you assign an object to
module.exports, that object will be the default export. -
Named Exports: When using
exports, each property or method becomes a named export, accessible by its name when imported.
Example with a Class:
// File: Logger.js
class Logger {
log(message) {
console.log(message);
}
}
module.exports = Logger;
// File: app.js
const Logger = require('./Logger');
const logger = new Logger();
logger.log('Hello, World!'); // Outputs: Hello, World!
In this example, the Logger class is exported from the Logger.js file and imported into app.js for use.
Your Feedback
Help us improve by sharing your thoughts
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.
