4th and 5th
4th and 5th
js Events
In Node.js, events are a key part of asynchronous programming. The EventEmitter class
(from the events module) allows objects to emit named events and register functions
(listeners) that respond to them.
Key Concepts:
Example:
js
CopyEdit
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {
console.log('An event occurred!');
});
myEmitter.emit('event');
🟨 Listeners in Node.js
Listeners are functions that are called when a specific event is emitted.
Types of Listeners:
js
CopyEdit
myEmitter.on('event', () => console.log('Listener 1'));
myEmitter.on('event', () => console.log('Listener 2'));
myEmitter.emit('event');
Output:
nginx
CopyEdit
Listener 1
Listener 2
js
CopyEdit
myEmitter.once('event', () => console.log('One-time listener'));
myEmitter.emit('event'); // Executes
myEmitter.emit('event'); // Ignored
js
CopyEdit
myEmitter.on('greet', (name, age) => {
console.log(`Hello, ${name}. You are ${age} years old.`);
});
myEmitter.emit('greet', 'Bob', 30);
Output:
sql
CopyEdit
Hello, Bob. You are 30 years old.
js
CopyEdit
const listener = () => console.log('This will be removed');
myEmitter.on('event', listener);
myEmitter.removeListener('event', listener);
🟠 Timers in Node.js
Node.js timers are used to schedule code execution.
1. setTimeout()
js
CopyEdit
setTimeout(() => {
console.log('Runs after 2 seconds');
}, 2000);
2. setInterval()
js
CopyEdit
const id = setInterval(() => {
console.log('Every 2 seconds');
}, 2000);
3. setImmediate()
js
CopyEdit
setImmediate(() => {
console.log('Executed after I/O events');
});
4. Clearing Timers:
● clearTimeout(id)
● clearInterval(id)
● clearImmediate(id)
🟣 Callbacks in Node.js
A callback is a function passed into another function as an argument to be executed later.
Example:
js
CopyEdit
function asyncTask(callback) {
setTimeout(() => {
callback(null, "Task complete");
}, 2000);
}
Error-First Callbacks:
js
CopyEdit
function divide(a, b, callback) {
if (b === 0) return callback(new Error("Cannot divide by zero"));
callback(null, a / b);
}
4o
You said:
How to handle data I/O in node js
ChatGPT said:
You can handle HTTP requests and send/receive data with built-in modules like http, or
more advanced frameworks like Express.js.
js
CopyEdit
const { MongoClient } = require('mongodb');
b. Writing to Terminal
js
CopyEdit
process.stdout.write('Type something: ');
✅ Summary
I/O Type Module/Tool Common Functions
Would you like help building a sample app that demonstrates file and database I/O together?
4o
You said:
next topic is accesing file systems for node js
ChatGPT said:
Great! Here's a clear guide on Accessing the File System in Node.js, which is commonly
done using the built-in fs module (File System module):
📘 1. Reading Files
a. Asynchronous (Non-blocking) — Preferred
js
CopyEdit
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) return console.error(err);
console.log(data);
});
📗 2. Writing Files
a. writeFile() (Async)
js
CopyEdit
fs.writeFile('newfile.txt', 'Hello, Node.js!', (err) => {
if (err) throw err;
console.log('File written successfully.');
});
b. appendFile()
js
CopyEdit
fs.appendFile('newfile.txt', '\nAppended line.', (err) => {
if (err) throw err;
console.log('Content appended.');
});
📕 3. Deleting Files
js
CopyEdit
fs.unlink('newfile.txt', (err) => {
if (err) throw err;
console.log('File deleted.');
});
c. Deleting a Directory
js
CopyEdit
fs.rmdir('myFolder', (err) => {
if (err) throw err;
console.log('Folder deleted.');
});
js
CopyEdit
const readStream = fs.createReadStream('large.txt');
const writeStream = fs.createWriteStream('output.txt');
🧾 Summary
Task Method
const io = socketIo(server);
socket.on('disconnect', () => {
console.log('Client disconnected:', socket.id);
});
});
server.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
🔷 What is NoSQL?
NoSQL databases are non-relational, designed for scalability, flexibility, and high
performance, especially for large-scale or real-time applications.
🔷 Key Features
● Distributed Architecture: Data is replicated across nodes for fault tolerance.
● Flexible Data Models: Schema-less structure supports dynamic and varied data.
🔷 Advantages
● ⚡ Scalability (horizontal)
● 🔧 Flexibility (schema-less)
● 💾 High Availability (replication)
● 🚀 Performance (low latency, high throughput)
● 🔄 Supports varied data models
Data Model Document, Key-Value, Column, Graph Tables (Rows and Columns)
bash
CopyEdit
2. Connecting to MongoDB
js
CopyEdit
mongoose.connect('mongodb://localhost:27017/mydatabase', {
useNewUrlParser: true,
useUnifiedTopology: true
js
CopyEdit
name: String,
email: String,
age: Number
});
4. CRUD Operations
➕ Create
js
CopyEdit
🔍 Read
js
CopyEdit
✏️ Update
js
CopyEdit
❌ Delete
js
CopyEdit
5. Advanced Querying
● .findOne(), .findById()
6. Error Handling
js
CopyEdit
try {
console.log(users);
} catch (error) {
await client.connect();
const db = client.db('mydb');
// Create
// Read
// Update
// Delete
await client.close();
run();
type: String,
},
email: {
type: String,
required: true,
unique: true,
validate: {
},
age: {
type: Number,
},
createdAt: {
type: Date,
default: Date.now
});
const User = model('User', userSchema);
name: 'Al',
email: '[email protected]',
age: 17
});
newUser.save()
.catch(err => {
} else {
});