πŸ“¦ Day 2: Node.js Modules β€” Core Modules, Custom Modules, require and exports

Payal PorwalPayal Porwal
4 min read

πŸ‘¨β€πŸ« What You’ll Learn Today:

  • What is a module in Node.js?

  • Core vs Custom Modules

  • How to use require and exports

  • Real-life examples

  • Practical tasks for hands-on learning


βœ… What is a Module?

A module in Node.js is like a small building block of code that performs a specific task.
You can think of it as a separate file that contains reusable logic.

πŸ“¦ Instead of writing all code in one file, we divide it into modules and import them wherever needed.


πŸ“‚ Types of Node.js Modules

TypeExampleDescription
Core Modulesfs, path, os, httpBuilt-in modules, come with Node.js
Custom ModulesYour own filesCreated by you for project-specific logic
Third-Partyexpress, lodash, etc.Installed via npm (we’ll cover this later)

πŸ”§ Core Modules – Built-in Features

Node.js gives us many useful modules out of the box.

Let’s explore 3 common ones:


1. fs (File System)

Used to read/write files.

const fs = require('fs');

fs.writeFileSync('hello.txt', 'Hello from Node.js!');

βœ… Output: Creates a file named hello.txt with content inside.


2. path

Used to work with file paths.

const path = require('path');

const filePath = path.join(__dirname, 'hello.txt');
console.log(filePath);

βœ… Output: Full path of hello.txt


3. os

Gives info about your computer system.

const os = require('os');

console.log("OS type:", os.type());
console.log("Free memory:", os.freemem());

βœ… Output: Your system type and available memory.


🧩 Custom Modules – Your Own Code

You can create your own modules in separate files and use them anywhere using require().


πŸ“ Example: Create a Calculator Module

➀ Step 1: Create a file calculator.js

// calculator.js

function add(a, b) {
  return a + b;
}

function subtract(a, b) {
  return a - b;
}

// Export functions to be used in other files
module.exports = {
  add,
  subtract
};

➀ Step 2: Create a file app.js to use this module

// app.js

const calc = require('./calculator');

console.log("Addition:", calc.add(5, 3));
console.log("Subtraction:", calc.subtract(10, 4));

🟒 Output:

Addition: 8
Subtraction: 6

πŸ’‘ require('./calculator') is used to import your custom module.


πŸ“š module.exports and require() in Detail

ConceptDescription
module.exportsUsed in a module to expose functions/variables so they can be used outside
require()Used to import the content of one module into another

πŸ‘‰ You can export a single function, object, or even class.


🎯 Real-Life Use Case: Utilities Module

Suppose you're building a blog backend, and you need a function to format the current date.

➀ utils.js

function getCurrentDate() {
  const date = new Date();
  return date.toLocaleDateString();
}

module.exports = { getCurrentDate };

➀ blog.js

const utils = require('./utils');

console.log("Post Date:", utils.getCurrentDate());

βœ… This makes your code reusable, clean, and modular.


πŸ’‘ Why Professionals Use Modules

  • Code Reusability

  • Better Structure in Large Projects

  • Easier Maintenance

  • Clean Separation of Concerns

βœ… In a real backend project, your code will be split into modules like:

  • routes

  • controllers

  • models

  • utilities

  • services


πŸ”„ Practice Tasks

  1. Create a module math.js with multiply and divide functions

  2. Use it in another file and print results

  3. Create a custom module info.js that exports your name, role, and institute


πŸ”š Summary

What You LearnedWhy It Matters
Core Modules (fs, os)Built-in power tools
Custom ModulesReusable, clean, organized code
module.exports, requireShare code across files
Real-world usageForms the base of large backend projects

πŸŽ“ You're now ready to build modular, scalable backend apps!

Would you like me to continue with Day 3: File System module (fs) – reading and writing files in the same detailed format?

10
Subscribe to my newsletter

Read articles from Payal Porwal directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Payal Porwal
Payal Porwal

Hi there, tech enthusiasts! I'm a passionate Software Developer driven by a love for continuous learning and innovation. I thrive on exploring new tools and technologies, pushing boundaries, and finding creative solutions to complex problems. What You'll Find Here On my Hashnode blog, I share: πŸš€ In-depth explorations of emerging technologies πŸ’‘ Practical tutorials and how-to guides πŸ”§Insights on software development best practices πŸš€Reviews of the latest tools and frameworks πŸ’‘ Personal experiences from real-world projects. Join me as we bridge imagination and implementation in the tech world. Whether you're a seasoned pro or just starting out, there's always something new to discover! Let’s connect and grow together! 🌟