Skip to main content

πŸ’š 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! πŸ’š