
Hey everyone! Welcome back. Today, we’re diving into something every Node.js developer needs to understand – Core Modules in Node.js.
What are Core Modules?
Why do we need them?
How do they help us build better applications?
In this video, I’ll answer these questions with real examples and code demos. Let’s get started!”*
What’s the Problem?
Imagine you’re building a backend system. You need to:
- Handle files
- Create a web server
- Work with file paths
- Get system information
You start installing external libraries, and before you know it, your project is bloated. Some libraries might be outdated, have security vulnerabilities, or be unnecessary for your needs.
This is exactly why Node.js provides Core Modules. Core Modules are pre-installed, optimized, and built into Node.js, so you don’t need to install anything extra. They’re fast, secure, and efficient.
Now, let’s break them down one by one.
File System (fs) Module – Reading & Writing Files
Let’s start with the fs module – the File System module. It allows us to read, write, and modify files in Node.js.
For example, let’s say we have a file called ‘data.txt’, and we want to read its content.”*
Example: Reading a File
const fs = require(‘fs’);
fs.readFile(‘data.txt’, ‘utf8’, (err, data) => {
if (err) {
console.error(‘Error reading file:’, err);
return;
}
console.log(‘File content:’, data);
});
Here, fs.readFile reads the file asynchronously. If there’s an error, it prints it. Otherwise, it logs the file content.”
Example: Writing to a File
fs.writeFile(‘output.txt’, ‘Hello, Node.js!’, (err) => {
if (err) throw err;
console.log(‘File written successfully!’);
});
“This writes ‘Hello, Node.js!’ into output.txt. Simple and efficient!”
HTTP Module – Creating a Web Server
A simple request-response diagram
*”Next, we have the http module, which allows us to create web servers in just a few lines of code.
Let’s say we want to create a basic server that sends a response when someone visits our site.
Example: Creating a Simple Web Server
const http = require(‘http’);
const server = http.createServer((req, res) => {
res.writeHead(200, { ‘Content-Type’: ‘text/plain’ });
res.end(‘Hello from Node.js Server!’);
});
server.listen(3000, () => {
console.log(‘Server running at http://localhost:3000/’);
});
“This creates a basic server running on port 3000. You can open your browser and visit http://localhost:3000 to see the response.”
Path Module – Managing File Paths
When working with files, you often need to deal with file paths. The path module helps manage these efficiently.
For example, let’s extract some information from a file path.
Example: Working with File Paths
CopyEdit
const path = require(‘path’);
const filePath = ‘/users/docs/file.txt’;
console.log(‘Directory:’, path.dirname(filePath));
console.log(‘File Name:’, path.basename(filePath));
console.log(‘Extension:’, path.extname(filePath));
“Now you know exactly where your files are and how to work with them.”
OS Module – System Information
CPU & Memory details
What if you need to check system information like CPU, memory, or platform? The os module has you covered.
This is useful when building applications that need to monitor system performance and you want to make some modification based on that.
Example: Fetching System Info
js
CopyEdit
const os = require(‘os’);
console.log(‘Platform:’, os.platform());
console.log(‘Total Memory:’, os.totalmem());
console.log(‘Free Memory:’, os.freemem());
console.log(‘CPU Info:’, os.cpus());
Visual: Console displaying system info
“This is useful when building applications that need to monitor system performance.”
Events Module – Handling Events
“Node.js is event-driven, meaning it reacts to things happening, like user clicks, data arriving, or errors occurring. The events module lets us handle custom events.”
Example: Creating an Event
const EventEmitter = require(‘events’);
const eventEmitter = new EventEmitter();
eventEmitter.on(‘greet’, () => {
console.log(‘Hello, Welcome to Node.js!’);
});
eventEmitter.emit(‘greet’);
This is useful for handling user actions, server responses, and more!
Summary & Call to Action
*”So, we covered the most important Core Modules in Node.js:
- fs – File handling
- http – Web servers
- path – File paths
- os – System info
- events – Event handling
Now it’s your turn! Try using these modules in a real project. If you found this helpful
——-
Without codes:
- What are Core Modules?
- Why do we need them?
- How do they help us build better applications?
By the end of this video, you’ll have a clear idea of why Core Modules are essential and how they simplify backend development. We will also explore Local Modules, which are custom modules that we create and import within our projects. And don’t worry—we’ll learn to implement everything step by step as we progress in this course. Let’s get started!”
What’s the Problem?
Imagine you’re building a backend system. You need to:
- Handle files
- Create a web server
- Work with file paths
- Get system information
You might think about installing external libraries for each of these tasks. But before you know it, your project is bloated with dependencies. Some might be outdated, introduce security vulnerabilities, or be unnecessary for your needs.
This is exactly why Node.js provides Core Modules – built-in, optimized, and ready to use. They are:
✅ Fast
✅ Secure
✅ Efficient
No need for extra installations – they are available right out of the box. Let’s explore them!
File System (fs) Module – Working with Files
One of the most common backend tasks is handling files – reading, writing, and modifying them. The fs module makes this easy.
Think about a situation where you need to store user data in a file or retrieve configuration settings. The fs module provides methods to interact with the file system efficiently.
💡 Example use cases:
- Reading configuration files
- Logging system activity
- Storing user-generated content
HTTP Module – Creating a Web Server
A backend isn’t complete without a way to communicate with users. The http module allows us to create web servers effortlessly.
Imagine someone visits your website. The server needs to:
- Listen for incoming requests.
- Process the request.
- Send an appropriate response.
The http module helps with all of this in just a few lines of code.
💡 Example use cases:
- Serving web pages dynamically
- Building REST APIs
- Handling form submissions
Path Module – Managing File Paths
When working with files, handling paths efficiently is crucial. Different operating systems use different path formats (Windows vs. Linux). The path module standardizes this.
For example, if you need to extract file details like:
- The directory name
- The file name
- The file extension
The path module makes it seamless!
💡 Example use cases:
- Constructing dynamic file paths
- Organizing project directories
- Handling file uploads
OS Module – Getting System Information
Sometimes, applications need to adapt based on system resources. The os module helps fetch system-related data like:
- CPU details
- Memory usage
- Platform information
This is especially useful for optimizing performance and system monitoring.
💡 Example use cases:
- Checking system health before launching an app
- Gathering analytics on resource usage
- Making dynamic optimizations
Events Module – Handling Events
Node.js is event-driven, meaning it reacts to actions like user clicks, data arrivals, or errors. The events module allows us to define and handle such events.
Think of it as setting up a notification system. When something happens, you can trigger a specific action.
💡 Example use cases:
- Handling user interactions (like button clicks)
- Managing real-time data (like chat applications)
- Logging server activities
Local Modules – Custom Modules for Our Projects
Apart from built-in core modules, we can also create our own custom modules, known as Local Modules. These allow us to:
- Structure our code better
- Reuse functionalities across different files
- Keep our application organized
For example, we could create a module for handling database connections or processing user authentication.
💡 Example use cases:
- Creating a custom logging module
- Reusing functions in different parts of the app
- Organizing business logic
Summary & Call to Action
“So, we covered the most important Core Modules in Node.js:
- fs – File handling
- http – Web servers
- path – File paths
- os – System info
- events – Event handling
- Local Modules – Custom modules we create