πŸ“¦ Day 4: Node.js Core Modules – path, os, and events

Payal PorwalPayal Porwal
4 min read

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

  • What are core modules in Node.js?

  • How to use the path module

  • How the os module helps with system info

  • How to work with events using the events module

  • Real-life practical examples

  • FAQs to clear your doubts


πŸ”Ή What Are Core Modules?

Core modules are built-in tools provided by Node.js.
You don't need to install them separately β€” just use require() to include them in your file.

Today we’ll learn 3 important ones:

  • path – To work with file and folder paths

  • os – To get system-related information

  • events – To create and handle custom events


πŸ“ 1. path Module – Handling File Paths

The path module is used to build and work with file and folder paths across different operating systems (Windows, Linux, macOS).


πŸ“Œ Example 1: Joining Paths

const path = require('path');

const fullPath = path.join(__dirname, 'files', 'info.txt');
console.log('Full Path:', fullPath);

βœ… path.join() safely combines folders/files into one full path.


πŸ“Œ Example 2: Get File Name and Extension

const filePath = '/home/user/app.js';

console.log('File Name:', path.basename(filePath));     // app.js
console.log('Extension:', path.extname(filePath));       // .js

πŸ“Œ Useful for:

  • Logging file uploads

  • File processing

  • Organizing folder structures


πŸ’» 2. os Module – System Info from Node.js

The os module gives you information about the operating system you are working on.


πŸ“Œ Example: Basic OS Info

const os = require('os');

console.log('OS Type:', os.type());             // e.g. Windows_NT
console.log('Platform:', os.platform());        // e.g. win32
console.log('Free Memory:', os.freemem());      // in bytes
console.log('Home Directory:', os.homedir());

πŸ“Œ Example: System Uptime

console.log('System Uptime (seconds):', os.uptime());

βœ… Useful in:

  • Monitoring apps

  • Logging server behavior

  • Displaying server dashboard info


πŸ”” 3. events Module – Handling Custom Events

The events module allows you to create your own events and respond to them β€” just like clicking a button in the browser triggers an event.


πŸ“Œ Step-by-Step Example:

const EventEmitter = require('events');  // Import
const emitter = new EventEmitter();      // Create instance

// Listener
emitter.on('userRegistered', (name) => {
  console.log(`Welcome, ${name}! Your account is ready.`);
});

// Trigger (emit) the event
emitter.emit('userRegistered', 'Payal');

βœ… Output:

Welcome, Payal! Your account is ready.

🧠 This is how backend apps handle:

  • Login success events

  • New order placed events

  • Email sent notifications

  • Custom logs


πŸ’Ό Real-Life Use Case (Mini Project Example)

Let’s create a simple event system for file download log:

const fs = require('fs');
const EventEmitter = require('events');
const emitter = new EventEmitter();

// Event listener
emitter.on('fileDownloaded', (fileName) => {
  fs.appendFileSync('download-log.txt', `Downloaded: ${fileName}\n`);
  console.log(`${fileName} logged successfully.`);
});

// Simulate file download
emitter.emit('fileDownloaded', 'resume.pdf');

βœ… This logs every file download into download-log.txt.


❓ FAQs – Common Doubts


1) Why do we use path.join() instead of string concatenation like __dirname + '/folder/file.txt'?

βœ… path.join() is cross-platform and automatically adds the correct separator (/ or \) depending on OS.
Manual concatenation may break your code on other systems.


2) What’s the difference between os.type() and os.platform()?

MethodWhat It Returns
os.type()OS name like Windows_NT, Linux
os.platform()Platform identifier like win32, darwin, linux

Use both for debugging or logging system environments.


3) Can we create multiple custom events using the events module?

βœ… Yes! You can create as many custom events as needed.
Each one should have a listener (.on) and emitter (.emit).

emitter.on('login', () => console.log('User logged in'));
emitter.emit('login');

4) Do I need to install path, os, or events?

❌ No need to install β€” these are core modules in Node.js.
Just import using require() like:

const path = require('path');

πŸ“ Practice Tasks for You

  1. Use path to get the name and extension of a file.

  2. Use os to log current system memory and platform.

  3. Create a custom event called userDeleted and print a goodbye message.

  4. Log system uptime using os.uptime().


βœ… Summary

ModulePurposeReal-Life Use
pathWork with file/folder pathsFile storage, uploads, project setup
osGet info about the system/OSMonitoring tools, dashboards
eventsCustom event handlingNotifications, logs, app actions

You're now ready to use system-level power tools in Node.js! 🎯


πŸ”” Stay Connected

If you found this article helpful and want to receive more such beginner-friendly and industry-relevant Node JS notes, tutorials, and project ideas β€” πŸ“© Subscribe to our newsletter by entering your email below.

And if you're someone who wants to prepare for tech interviews while having a little fun and entertainment, πŸŽ₯ Don’t forget to subscribe to my YouTube channel – Knowledge Factory 22 – for regular content on tech concepts, career tips, and coding insights!

Stay curious. Keep building. πŸš€

0
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! 🌟