Nearby lessons
4 of 21📦 Node.js – Import & Use Functions from Another File
📌 What are Modules?
What are Modules in Node.js?
In Node.js, any file with a .js extension is a module.
Modules allow you to split your code into multiple files for better organization,
reusability, and easier debugging.
Functions, classes, or objects defined in one module can be
imported and reused in other files using require().
📌 Why Use Modules?
- Helps in organizing large applications
- Code becomes reusable across multiple files
- Easy to debug and maintain
- Supports modularization by splitting logic into multiple files
⚙️ Creating a Module
Every JavaScript file in Node.js is a module.
Let's create a file sum.js that exports a single function.
📦 Exporting Multiple Functions
You can export multiple functions as an object from a module.
🔓 Destructuring While Importing
Instead of using dot notation, you can use destructuring to directly access exported functions.
🧩 Exporting Functions Individually
Each function can be exported separately using module.exports.
⚡ Using exports Shortcut
You can also use the exports keyword instead of module.exports.
📂 Importing from a Directory
You can also organize modules inside directories.
For example, move sum.js inside a maths/ folder and require it with path.