0% found this document useful (0 votes)
7 views4 pages

Nodejs Advanced Sections9

Node Section 9

Uploaded by

Aditya
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)
7 views4 pages

Nodejs Advanced Sections9

Node Section 9

Uploaded by

Aditya
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/ 4

Node.

js Interview Guide: Sections 9-12

Section 9: Advanced Node.js Concepts

9.1 Event Loop and Async Operations

Node.js is single-threaded but handles concurrency using the event loop.

How it works:

1. Call Stack – Executes synchronous code.


2. Event Loop – Monitors the call stack and callback queue.
3. Callback Queue – Stores callbacks from async operations like fs.readFile or setTimeout .
4. Microtasks Queue – Handles process.nextTick and Promises before moving to callback
queue.

Example:

console.log("Start");
setTimeout(() => console.log("setTimeout"), 0);
process.nextTick(() => console.log("nextTick"));
Promise.resolve().then(() => console.log("Promise"));
console.log("End");

Output:

Start
End
nextTick
Promise
setTimeout

9.2 process.nextTick(), setImmediate(), setTimeout()

Function Execution Timing

process.nextTick() After current operation, before event loop continues

setImmediate() At the end of the current event loop iteration

setTimeout(fn, 0) After at least 0ms, added to timers queue

9.3 Streams in Node.js

Streams are used for efficient handling of large data. Types: Readable, Writable, Duplex, Transform

1
Example:

const fs = require('fs');
const readStream = fs.createReadStream('largeFile.txt', 'utf-8');
const writeStream = fs.createWriteStream('copy.txt');
readStream.on('data', chunk => writeStream.write(chunk));
readStream.on('end', () => console.log('File copy complete'));

9.4 Error Handling

Callback Example:

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


if (err) console.error(err);
else console.log(data);
});

Async/Await Example:

const fs = require('fs').promises;
async function readFile() {
try { const data = await fs.readFile('file.txt', 'utf8');
console.log(data); }
catch(err) { console.error(err); }
}
readFile();

9.5 Worker Threads

const { Worker, isMainThread, parentPort } = require('worker_threads');


if(isMainThread){
const worker = new Worker(__filename);
worker.on('message', msg => console.log(msg));
}else{
parentPort.postMessage('Hello from worker');
}

9.6 Caching

const NodeCache = require('node-cache');


const cache = new NodeCache({ stdTTL: 100 });
cache.set("user_1", { name: "Aditya" });
console.log(cache.get("user_1"));

2
9.7 Cluster Module

const cluster = require('cluster');


const http = require('http');
const numCPUs = require('os').cpus().length;
if(cluster.isMaster){
for(let i=0;i<numCPUs;i++) cluster.fork();
}else{
http.createServer((req,res)=>res.end(`Worker ${process.pid}
`)).listen(8000);
}

Section 10: Performance Optimization & Monitoring

10.1 Profiling

• Use node --inspect or clinic.js to find CPU/memory bottlenecks.

10.2 Caching

• Use Redis or in-memory cache to store frequently requested data.

10.3 Load Balancing

• Use nginx or Node cluster module to distribute requests across CPU cores.

10.4 Monitoring

• Tools: PM2 , NewRelic , Datadog for metrics and logs.

Example (PM2):

pm install pm2 -g
pm2 start app.js --name myapp
pm2 monit

Section 11: Microservices & Event-Driven Architecture

11.1 Microservices

• Break monolithic apps into smaller services.


• Communicate via HTTP/REST or gRPC.

Example:

3
// user-service.js
app.get('/user/:id', (req,res)=>res.json({id:req.params.id,name:'Aditya'}));

11.2 Event-Driven Architecture

• Services communicate via events (Kafka, RabbitMQ).

Example:

// Event emitter in Node


const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('user_created', data => console.log('User Created:', data));
emitter.emit('user_created', {id:1,name:'Aditya'});

Section 12: Real-Time Applications with WebSocket & Socket.io

12.1 WebSocket

• Full-duplex communication for real-time apps.

Example:

const WebSocket = require('ws');


const server = new WebSocket.Server({ port: 8080 });
server.on('connection', ws => {
ws.on('message', msg => console.log('Received:', msg));
ws.send('Hello client');
});

12.2 Socket.io

• Provides fallback options if WebSocket is unavailable.

Example:

const io = require('socket.io')(3000);
io.on('connection', socket => {
console.log('User connected');
socket.on('message', msg => socket.emit('message', msg));
});

Use case: Chat apps, live notifications, multiplayer games.

You might also like