Day 2: Understanding Core Modules and the Event Loop: Using Modules and npm

Search for a command to run...

No comments yet. Be the first to comment.
Let’s build a Secure Personal AI API with Ollama, Nginx, and Cloudflare Tunnel using oracle ubuntu instance Prerequisites and Target Audience ⚠️ Important Notice: This is not a beginner-friendly tutorial. This guide assumes you have practical, hands-...

Introduction Running applications on Oracle Cloud Infrastructure (OCI) requires more than just starting your server—you need a robust setup that ensures your services stay running, restart automatically after crashes, and survive system reboots. This...

Ever found yourself in one of these situations? "Can you check my website?" but your app is running on localhost:3000 Need to test webhooks from external services but they can't reach your local machine Want to show a client your work-in-progress ...

This article walks you through every single file required to get a secure, refresh-token-enabled JWT authentication system in NestJS with Prisma, bcrypt, Passport, and class-validator.Copy / paste the snippets in order and you will have a working pro...

Introduction to Amazon EC2 Compute refers to the processing power needed to run applications, manage data, and perform calculations. In the cloud, this power is available on-demand. You can access it remotely without owning or maintaining physical ha...
Node.js core modules (e.g., fs, path, http, os)
Understanding the Event Loop
Synchronous vs Asynchronous programming in Node.js
Practical: Basic file operations using fs module (read, write, append)
Handling paths with path module
Timing events with setTimeout and setInterval
What is the Event Loop?
Example of Event Loop:
console.log('Start');
setTimeout(() => {
console.log('Timeout function executed');
}, 2000);
console.log('End');
Synchronous:
Example of Synchronous Code:
const fs = require('fs');
console.log('Start reading file...');
const data = fs.readFileSync('example.txt', 'utf-8');
console.log(data);
console.log('Finished reading file.');
Asynchronous:
Example of Asynchronous Code:
const fs = require('fs');
console.log('Start reading file...');
fs.readFile('example.txt', 'utf-8', (err, data) => {
if (err) throw err;
console.log(data);
});
console.log('Finished reading file.');
fs Modulefs (File System) module:
Allows working with the file system, such as reading, writing, and appending to files.
Reading a File (Asynchronous):
const fs = require('fs');
fs.readFile('example.txt', 'utf-8', (err, data) => {
if (err) throw err;
console.log('File contents:', data);
});
Writing to a File (Asynchronous):
const fs = require('fs');
fs.writeFile('output.txt', 'Hello, Node.js!', (err) => {
if (err) throw err;
console.log('File written successfully.');
});
Appending to a File (Asynchronous):
const fs = require('fs');
fs.appendFile('output.txt', '\nAppended text.', (err) => {
if (err) throw err;
console.log('Text appended successfully.');
});
path Modulepath module:
Helps with working with file and directory paths. It's especially useful when you need to manipulate or join paths across platforms.
Joining Paths:
const path = require('path');
const fullPath = path.join(__dirname, 'files', 'example.txt');
console.log('Full Path:', fullPath);
Getting File Name from Path:
const path = require('path');
const filePath = '/users/documents/example.txt';
console.log('File Name:', path.basename(filePath));
Getting Directory Name from Path:
const path = require('path');
const filePath = '/users/documents/example.txt';
console.log('Directory Name:', path.dirname(filePath));
setTimeout and setIntervalsetTimeout: Runs a function after a certain delay (once).
setTimeout(() => {
console.log('This runs after 3 seconds');
}, 3000); // 3000 milliseconds = 3 seconds
setInterval: Runs a function repeatedly after a specified interval.
setInterval(() => {
console.log('This runs every 2 seconds');
}, 2000); // 2000 milliseconds = 2 seconds
Clearing Intervals:
const intervalId = setInterval(() => {
console.log('Repeating...');
}, 1000);
setTimeout(() => {
clearInterval(intervalId);
console.log('Stopped interval');
}, 5000); // Stop after 5 seconds
What is Modular Programming?
Node.js uses CommonJS module system, which includes:
require(): Used to load modules.
module.exports: Used to export functionality from a module so other files can use it.
Creating a module:
Using require() to load a module:
require().Example:
// math.js (your custom module)
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
// Exporting the functions
module.exports = { add, subtract };
add and subtract functions from math.js in another file: // main.js
const math = require('./math');
console.log(math.add(5, 3)); // Output: 8
console.log(math.subtract(10, 7)); // Output: 3
What is npm?
npm (Node Package Manager) is the default package manager for Node.js. It helps install, manage, and share reusable packages of code.
npm allows you to easily download and integrate thousands of third-party libraries (packages) like lodash, axios, etc., into your project.
Package Management:
package.json and DependenciesWhat is package.json?
package.json is a file that holds metadata about your Node.js project (like project name, version, and dependencies). It is automatically generated when you run the npm init command.Dependencies:
package.json so they can be easily installed on any machine using npm install.Task 1: File Operations
What to do:
Create a new file called notes.txt and write "Learning Node.js" into it.
Read and display the content of notes.txt.
Append "Node.js is awesome!" to the same file and read it again.
Task 2: Path Operations
What to do:
Use the path module to print the full path of your notes.txt file.
Extract and print only the file name from the path.
Extract and print the directory name from the path.
Task 3: Timing Events
What to do:
Write a setTimeout function to print "Hello after 3 seconds."
Use setInterval to print "Learning is fun!" every 2 seconds and stop it after 10 seconds using clearInterval.
Reflection:
Node.js Official Documentation
Understanding the Node.js Event Loop
Theory: Focus on core modules like fs, path, and the Node.js event loop.
Practical: Perform file operations, handle paths, and understand timing events with setTimeout and setInterval.
Tasks: Reinforce learning by writing and manipulating files, handling paths, and experimenting with asynchronous timers.