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.

Example03
Loading editor…

📦 Exporting Multiple Functions

You can export multiple functions as an object from a module.

Example04
Loading editor…

🔓 Destructuring While Importing

Instead of using dot notation, you can use destructuring to directly access exported functions.

Example05
Loading editor…

🧩 Exporting Functions Individually

Each function can be exported separately using module.exports.

Example06
Loading editor…

⚡ Using exports Shortcut

You can also use the exports keyword instead of module.exports.

Example07
Loading editor…

📂 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.

Example08
Loading editor…

🧠 Test Your Knowledge

4 Questions
Progress: 0 / 4