Export and Import in Node.js
Learn how to share functions, variables and objects between JavaScript files using CommonJS exports and ES Module imports.
1. What Are Export and Import?
In a Node.js application, we often create multiple JavaScript files to keep the application organized. Sometimes, a function or variable created in one file needs to be used in another file.
Export means making functionality available outside its module. Import means loading or accessing functionality that another module has exported.
For example, an application may contain:
math.js— contains calculation functions.student.js— contains student-related functionality.app.js— uses functions from other files.
2. Why Do We Need Export and Import?
- Code Reusability: Use the same function in different files.
- Less Duplication: Avoid writing the same logic repeatedly.
- Better Organization: Keep related functions in separate files.
- Easy Maintenance: Update a function in one place.
- Readable Code: Keep the main application file simple.
- Teamwork: Different developers can work on different modules.
3. How Export and Import Work
The following diagram explains how one file shares a function and another file uses it.
math.js
Defines the addition function.
function add(a, b) { ... }
Share the Function
module.exports = add;
Makes the function available to another CommonJS module.
app.js
const add = require("./math");
Loads the exported function.
Execute the Function
add(10, 20)
Result: 30
4. Export and Import Using CommonJS
CommonJS is a module system traditionally used in Node.js.
It uses module.exports to expose functionality
and require() to load that functionality.
Step 1: Create math.js
function add(a, b) {
return a + b;
}
module.exports = add;
The add() function accepts two numbers and returns
their sum. The statement module.exports = add
exports the function.
Step 2: Create app.js
const add = require("./math");
const result = add(10, 20);
console.log("Addition:", result);
Expected Output
Addition: 30
Explanation
math.jsdefines the function.module.exportsmakes the function available outside the module.require("./math")loads the exported function.add(10, 20)calls the function.console.log()displays the result.
5. Export Multiple Functions
We can export multiple functions together as properties of an object. This is useful when several functions belong to the same feature.
Step 1: Create calculator.js
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
function multiply(a, b) {
return a * b;
}
module.exports = {
add,
subtract,
multiply
};
Step 2: Import Functions in app.js
const calculator = require("./calculator");
console.log("Addition:", calculator.add(20, 10));
console.log("Subtraction:", calculator.subtract(20, 10));
console.log("Multiplication:", calculator.multiply(20, 10));
Expected Output
Addition: 30 Subtraction: 10 Multiplication: 200
Since the module exports an object, the importing file accesses each function through its property name using dot notation.
6. Import Multiple Functions Using Destructuring
Object destructuring lets us extract selected functions directly
from the object returned by require().
const { add, subtract } = require("./calculator");
console.log(add(15, 5));
console.log(subtract(15, 5));
Expected Output
20 10
Here, add and subtract are extracted
from the exported object. Their names match the exported
property names.
7. Export and Import Using ES Modules
ES Modules use the export keyword to share
functionality and the import keyword to use
that functionality in another file.
Step 1: Create math.mjs
export function add(a, b) {
return a + b;
}
export function multiply(a, b) {
return a * b;
}
Step 2: Create app.mjs
import { add, multiply } from "./math.mjs";
console.log("Addition:", add(10, 20));
console.log("Multiplication:", multiply(10, 20));
Expected Output
Addition: 30 Multiplication: 200
The curly braces in the import statement select the named exports that the file needs. The imported functions can then be called like normal JavaScript functions.
.mjs
extension so Node.js identifies both files as ES Modules.
A project can also use .js files with suitable
package configuration.
8. Named Export and Default Export
ES Modules support named exports and default exports. A named export is imported using its exported name, while a default export is imported without curly braces.
Example: Default Export
export default function greet(name) {
return "Hello, " + name + "!";
}
Import the Default Export
import greet from "./greeting.mjs";
console.log(greet("Student"));
Expected Output
Hello, Student!
| Feature | Named Export | Default Export |
|---|---|---|
| Export syntax | export function add() { ... } |
export default function greet() { ... } |
| Import syntax | import { add } from "./math.mjs"; |
import greet from "./greeting.mjs"; |
| Number per module | Multiple named exports are allowed. | Only one default export is allowed. |
9. CommonJS vs ES Modules Flow
Both module systems allow files to share functionality, but they use different syntax.
Export
module.exports = add;
Import
require("./math");
CommonJS module system
Export
export function add() { ... }
Import
import { add } from "./math.mjs";
Standard JavaScript module system
10. Common Mistakes
| Mistake | Correct Approach |
|---|---|
| Forgetting to export a function. | Export the function before trying to import it. |
| Using an incorrect file path. | Check the relative path and filename. |
| Using curly braces incorrectly for a default import. | Use curly braces for named imports, not for the default import. |
| Mixing CommonJS and ES Module syntax without checking configuration. | Verify the module system used by the project. |
| Using a property name that was not exported. | Check the exported names and match them when importing. |
11. Practice Tasks
Task 1: Calculator Module
Create a calculator module with addition and subtraction functions. Export both functions and use them in another file.
Expected Output:Addition: 30
Subtraction: 10
Task 2: Student Details
Create a module that exports a function returning a student's name and course. Import the function in another file and display the details.
Expected Output:Student: Samadhan
Course: Node.js
Task 3: Greeting Module
Create a default-exported greeting function and import it into another file. Pass a name to the function and display the returned message.
Expected Output:Hello, Student!
Summary
Export and import allow JavaScript files to share reusable functionality in Node.js applications. CommonJS uses module.exports to expose functions and values and require() to load them into another file. ES Modules use export and import, supporting both named exports and default exports. Named imports select specific exported values, while default imports load the module's primary exported value. These mechanisms improve code reusability, organization, readability and maintainability in Node.js projects.