π What is Node.js?
π Definitionβ
Node.js is a JavaScript runtime built on Chrome's V8 engine. It enables JavaScript execution outside browsers with asynchronous event-driven architecture for high performance and scalability. Provides vast library ecosystem through npm (Node Package Manager).
π― Simple Analogyβ
Restaurant Kitchenβ
Traditional Server (Synchronous)
ββ One chef serves customers one by one (slow)
Node.js (Asynchronous)
ββ One chef handles multiple orders simultaneously
ββ While steak cooks β prepare salad
ββ Fast and efficient!
βοΈ Event Loopβ
βββββββββββββββ
β Call Stack β Executing code
ββββββββ¬βββββββ
β
ββββββββΌβββββββ
β Event Loop β Coordinator
ββββββββ¬βββββββ
β
ββββββ΄ββββββ
β β
Microtask Task Queue
(Promise) (setTimeout)
π‘ Key Examplesβ
Basic HTTP Serverβ
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>Hello, Node.js!</h1>');
});
server.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
Express APIβ
const express = require('express');
const app = express();
app.use(express.json());
app.get('/api/users', (req, res) => {
res.json([
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' }
]);
});
app.post('/api/users', (req, res) => {
const newUser = req.body;
res.status(201).json({ message: 'Created', user: newUser });
});
app.listen(3000);
Async/Awaitβ
const fs = require('fs').promises;
// β Sequential (slow)
async function readSequential() {
const file1 = await fs.readFile('file1.txt');
const file2 = await fs.readFile('file2.txt');
// Total: 200ms
}
// β
Parallel (fast)
async function readParallel() {
const [file1, file2] = await Promise.all([
fs.readFile('file1.txt'),
fs.readFile('file2.txt')
]);
// Total: 100ms (concurrent)
}
Database Integrationβ
const express = require('express');
const mysql = require('mysql2/promise');
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'password',
database: 'mydb'
});
app.get('/api/users', async (req, res) => {
try {
const [rows] = await pool.execute('SELECT * FROM users');
res.json(rows);
} catch (error) {
res.status(500).json({ error: 'Database error' });
}
});
π€ FAQβ
Q1. Why is Node.js fast?β
// Non-blocking I/O
readFile('file.txt', (err, data) => {
processData(data);
});
// Can handle other requests while reading!
// Event-driven
// Single thread handles thousands of connections
// No context switching overhead
Q2. What is npm?β
# Package manager for Node.js
npm install express # Install package
npm init -y # Initialize project
npm list # List installed packages
npm audit # Security check
# package.json
{
"dependencies": {
"express": "^4.18.0"
}
}
Q3. CommonJS vs ES Modules?β
// CommonJS (traditional)
const { add } = require('./math');
module.exports = { add };
// ES Modules (modern)
import { add } from './math.js';
export function add(a, b) { return a + b; }
// Enable in package.json
{ "type": "module" }
π¬ Summaryβ
- Asynchronous I/O: High performance and scalability
- JavaScript: Same language as frontend
- npm: Vast package ecosystem
- Event Loop: Efficient concurrent processing
Become a full-stack developer with Node.js! π