0% found this document useful (0 votes)
9 views19 pages

4th and 5th

The document provides an overview of key concepts in Node.js, including event handling with the EventEmitter class, timers, callbacks, and data I/O operations. It covers file system access using the fs module, real-time communication with WebSockets, and an introduction to NoSQL databases, particularly MongoDB. Additionally, it outlines CRUD operations and error handling when manipulating MongoDB from Node.js.

Uploaded by

lastmail1124
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views19 pages

4th and 5th

The document provides an overview of key concepts in Node.js, including event handling with the EventEmitter class, timers, callbacks, and data I/O operations. It covers file system access using the fs module, real-time communication with WebSockets, and an introduction to NoSQL databases, particularly MongoDB. Additionally, it outlines CRUD operations and error handling when manipulating MongoDB from Node.js.

Uploaded by

lastmail1124
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

🟢 Node.

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:

●​ EventEmitter is used to create and handle events.​

●​ .on() adds a listener for an event.​

●​ .emit() triggers the event.​

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:

1.​ Multiple 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

2.​ One-Time Listeners:​

js
CopyEdit
myEmitter.once('event', () => console.log('One-time listener'));
myEmitter.emit('event'); // Executes
myEmitter.emit('event'); // Ignored

3.​ Listeners with Arguments:​

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.

4.​ Removing Listeners:​

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()

Executes a function once after a delay.

js
CopyEdit
setTimeout(() => {
console.log('Runs after 2 seconds');
}, 2000);

2. setInterval()

Executes a function repeatedly at a fixed interval.

js
CopyEdit
const id = setInterval(() => {
console.log('Every 2 seconds');
}, 2000);

setTimeout(() => clearInterval(id), 6000); // Stops after 6 sec

3. setImmediate()

Runs a function after the current event loop.

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);
}

asyncTask((err, result) => {


if (err) return console.error("Error:", err);
console.log(result);
});

Error-First Callbacks:

This is a standard pattern in Node.js:

js
CopyEdit
function divide(a, b, callback) {
if (b === 0) return callback(new Error("Cannot divide by zero"));
callback(null, a / b);
}

divide(10, 2, (err, result) => {


if (err) console.error(err.message);
else console.log("Result:", result);
});
Would you like a visual cheat sheet or code snippet examples for practice?

4o

You said:
How to handle data I/O in node js

ChatGPT said:

Handling Data I/O (Input/Output) in Node.js is primarily asynchronous and non-blocking,


making it well-suited for applications that handle a lot of I/O operations such as reading files,
handling network requests, or accessing databases.

Here's a breakdown of how to handle different types of data I/O in Node.js:

📁 1. File I/O (Using fs Module)


a. Reading a File (Async)
js
CopyEdit
const fs = require('fs');

fs.readFile('example.txt', 'utf8', (err, data) => {


if (err) return console.error('Error reading file:', err);
console.log('File contents:', data);
});

b. Writing to a File (Async)


js
CopyEdit
fs.writeFile('output.txt', 'Hello, Node.js!', (err) => {
if (err) return console.error('Error writing file:', err);
console.log('File written successfully');
});

c. Using Streams for Large Files


js
CopyEdit
const readStream = fs.createReadStream('largefile.txt');
readStream.on('data', (chunk) => {
console.log('Received chunk:', chunk.toString());
});

🌐 2. Network I/O (HTTP Server Example)


js
CopyEdit
const http = require('http');

const server = http.createServer((req, res) => {


res.write('Hello from Node.js Server!');
res.end();
});

server.listen(3000, () => console.log('Server running on port


3000'));

You can handle HTTP requests and send/receive data with built-in modules like http, or
more advanced frameworks like Express.js.

🗃️ 3. Database I/O (e.g., MongoDB)


Using mongodb or Mongoose to read/write data asynchronously:

js
CopyEdit
const { MongoClient } = require('mongodb');

async function run() {


const client = new MongoClient('mongodb://localhost:27017');
try {
await client.connect();
const db = client.db('testdb');
const collection = db.collection('users');
await collection.insertOne({ name: 'Alice', age: 30 });
const users = await collection.find().toArray();
console.log(users);
} finally {
await client.close();
}
}
run();

⚙️ 4. Standard Input/Output (Terminal I/O)


a. Reading from Terminal
js
CopyEdit
process.stdin.on('data', (data) => {
console.log('You typed:', data.toString());
});

b. Writing to Terminal
js
CopyEdit
process.stdout.write('Type something: ');

✅ Summary
I/O Type Module/Tool Common Functions

File I/O fs readFile, writeFile,


streams

Network I/O http, https createServer, request

Database mongodb, connect, query,


I/O mysql insertOne

Terminal I/O process.st on('data'),


din stdout.write()

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):

📁 Accessing the File System in Node.js


The fs module allows you to interact with the file system: reading, writing, updating,
deleting, and renaming files or directories.

🔧 Importing the Module


js
CopyEdit
const fs = require('fs');

📘 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);
});

b. Synchronous (Blocking) — Not recommended for large-scale apps


js
CopyEdit
const data = fs.readFileSync('example.txt', 'utf8');
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()

Adds content to an existing file:

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.');
});

📙 4. Working with Directories


a. Creating a Directory
js
CopyEdit
fs.mkdir('myFolder', (err) => {
if (err) throw err;
console.log('Folder created.');
});

b. Reading Contents of a Directory


js
CopyEdit
fs.readdir('./', (err, files) => {
if (err) throw err;
console.log('Directory contents:', files);
});

c. Deleting a Directory
js
CopyEdit
fs.rmdir('myFolder', (err) => {
if (err) throw err;
console.log('Folder deleted.');
});

🔐 Note: fs.promises is available if you prefer async/await over callbacks.

⚙️ Advanced: File Streams


Streams are used for handling large files efficiently.

js
CopyEdit
const readStream = fs.createReadStream('large.txt');
const writeStream = fs.createWriteStream('output.txt');

readStream.pipe(writeStream); // Copies content

🧾 Summary
Task Method

Read File fs.readFile()

Write File fs.writeFile()

Append File fs.appendFile()

Delete File fs.unlink()

Create Directory fs.mkdir()


Read Directory fs.readdir()

Delete Directory fs.rmdir()

Use Streams fs.createReadStream() /


fs.createWriteStream()

next topic implmenting socket services in node.js

Node.js enables real-time bidirectional communication using WebSockets, most commonly


via the socket.io library.

const http = require('http');


const fs = require('fs');
const socketIo = require('socket.io');

// Create HTTP server that serves an HTML page


const server = http.createServer((req, res) => {
fs.readFile('index.html', (err, data) => {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data);
});
});

const io = socketIo(server);

io.on('connection', socket => {


console.log('Client connected:', socket.id);

socket.on('msg', data => {


console.log('Client says:', data);
socket.emit('reply', 'Hello from 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.​

●​ High Availability: Built-in replication ensures uptime.​

●​ Flexible Data Models: Schema-less structure supports dynamic and varied data.​

🔷 Types of NoSQL Databases


Type Description Example Advantages

Document-B JSON/BSON documents MongoDB, Flexible, stores complex


ased with nested structure CouchDB objects

Key-Value Simple key-value pairs Redis, Extremely fast, good for


Store DynamoDB caching & sessions

Column-Fam Data stored in columns; Cassandra, Write-optimized, scalable,


ily grouped in families HBase ideal for analytics

Graph Nodes and relationships Neo4j, Great for connected data


Database (edges) with properties Neptune (e.g., social networks)

🔷 When to Use NoSQL


●​ Need horizontal scaling​

●​ Data structure is dynamic or unstructured​

●​ Require low-latency and high-throughput​

●​ Working with real-time or big data applications​

🔷 Advantages
●​ ⚡ Scalability (horizontal)​
●​ 🔧 Flexibility (schema-less)​
●​ 💾 High Availability (replication)​
●​ 🚀 Performance (low latency, high throughput)​
●​ 🔄 Supports varied data models​

🔷 NoSQL vs SQL Comparison


Feature NoSQL SQL

Data Model Document, Key-Value, Column, Graph Tables (Rows and Columns)

Schema Flexible (schema-less) Fixed (schema-based)

Scalability Horizontal Vertical

Transaction Limited ACID, eventual consistency Full ACID support


s

Use Cases Big Data, Real-Time, Dynamic Structured data, Complex


joins

Examples MongoDB, Cassandra, Redis MySQL, PostgreSQL, Oracle

next topic manipulating mongo db from node js


1. Setup: Installing Required Packages

bash

CopyEdit

npm install mongoose

2. Connecting to MongoDB

js

CopyEdit

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/mydatabase', {

useNewUrlParser: true,

useUnifiedTopology: true

}).then(() => console.log("MongoDB connected"))

.catch(err => console.log("Connection error:", err));

3. Defining a Schema and Model

js

CopyEdit

const userSchema = new mongoose.Schema({

name: String,

email: String,

age: Number
});

const User = mongoose.model('User', userSchema);

4. CRUD Operations

➕ Create
js

CopyEdit

const newUser = new User({ name: 'Alice', email:


'[email protected]', age: 30 });

newUser.save().then(doc => console.log(doc)).catch(err =>


console.error(err));

🔍 Read
js

CopyEdit

User.find({ age: { $gt: 20 } }).then(users => console.log(users));

✏️ Update
js

CopyEdit

User.updateOne({ name: 'Alice' }, { $set: { age: 31 } })

.then(result => console.log(result));

❌ Delete
js

CopyEdit

User.deleteOne({ name: 'Alice' }).then(result =>


console.log(result));

5. Advanced Querying

●​ .findOne(), .findById()​

●​ .sort(), .limit(), .skip()​

●​ Use operators: $gt, $lt, $in, $regex, etc.​

6. Error Handling

Use .catch() or try-catch with async/await for robust error handling.

js

CopyEdit

try {

const users = await User.find();

console.log(users);

} catch (error) {

console.error("Query failed:", error);

const { MongoClient } = require('mongodb');

const url = 'mongodb://localhost:27017';

const client = new MongoClient(url);


async function run() {

await client.connect();

const db = client.db('mydb');

const users = db.collection('users');

// Create

await users.insertOne({ name: 'Bob', email: '[email protected]', age: 28 });

// Read

const user = await users.findOne({ name: 'Bob' });

// Update

await users.updateOne({ name: 'Bob' }, { $set: { age: 29 } });

// Delete

await users.deleteOne({ name: 'Bob' });

await client.close();

run();

const { Schema, model } = require('mongoose');

const userSchema = new Schema({


name: {

type: String,

required: [true, 'Name is required'],

minlength: [3, 'Name must be at least 3 characters long'],

maxlength: [50, 'Name must be less than 50 characters']

},

email: {

type: String,

required: true,

unique: true,

validate: {

validator: v => /^[\w.-]+@[\w.-]+\.\w{2,}$/.test(v),

message: props => `${props.value} is not a valid email!`

},

age: {

type: Number,

min: [18, 'Minimum age is 18'],

max: [100, 'Maximum age is 100']

},

createdAt: {

type: Date,

default: Date.now

});
const User = model('User', userSchema);

const newUser = new User({

name: 'Al',

email: '[email protected]',

age: 17

});

newUser.save()

.then(doc => console.log('Saved:', doc))

.catch(err => {

if (err.name === 'ValidationError') {

console.log('Validation failed:', err.errors);

} else {

console.log('Other error:', err);

});

You might also like