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.

Node.js Environment
RUNTIME ACTIVE
const add = require('./sum.js');

console.log("add(2,3) =", add(2, 3));
console.log("add(5,3) =", add(5, 3));

Terminal Output
Live Output Preview

📦 Exporting Multiple Functions

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

Node.js Environment
RUNTIME ACTIVE
const calculator = require('./sum');

console.log("sum(2,3) =", calculator.sum(2, 3));
console.log("sub(5,3) =", calculator.sub(5, 3));

Terminal Output
Live Output Preview

🔓 Destructuring While Importing

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

Node.js Environment
RUNTIME ACTIVE
const { sum, sub } = require('./sum');

console.log("sum(2,3) =", sum(2, 3));
console.log("sub(5,3) =", sub(5, 3));

Terminal Output
Live Output Preview

🧩 Exporting Functions Individually

Each function can be exported separately using module.exports.

Node.js Environment
RUNTIME ACTIVE
const calculator = require('./sum');

console.log("sum(10,5) =", calculator.sum(10, 5));
console.log("sub(10,5) =", calculator.sub(10, 5));

Terminal Output
Live Output Preview

⚡ Using exports Shortcut

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

Node.js Environment
RUNTIME ACTIVE
const calculator = require('./sum');

console.log("sum(20,10) =", calculator.sum(20, 10));
console.log("sub(20,10) =", calculator.sub(20, 10));

Terminal Output
Live Output Preview

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

Node.js Environment
RUNTIME ACTIVE
const calculator = require('./maths/sum');

console.log("sum(4,6) =", calculator.sum(4, 6));
console.log("sub(9,4) =", calculator.sub(9, 4));

Terminal Output
Live Output Preview

🧠 Test Your Knowledge

4 Questions

Progress: 0 / 4
Keep Going!Types of Node.js Modules