Comprehensive Guide to Node.js
Node.js is a JavaScript runtime built on Chrome's V8 engine. It enables developers to use JavaScript on the server-side to build scalable and high-performance applications. Node.js is especially suited for I/O-heavy operations such as web APIs and real-time services.
Core Concepts of Node.js
- Non-blocking I/O: Node.js performs asynchronous I/O operations, allowing other tasks to run in parallel. For example, when reading a file, the server can handle other requests without waiting for the file read operation to finish.
- Event Loop: Node.js uses a single-threaded event loop to manage asynchronous operations. This model allows it to handle thousands of concurrent connections efficiently by queuing events and processing them as callbacks.
- Modular Architecture: Code is structured into modules using CommonJS (
requireandmodule.exports). Each file is treated as a separate module, which promotes reusability and maintainability.
Important Topics
-
File System (fs module):
The
fsmodule allows for interacting with the file system. Example:
This reads a file asynchronously without blocking the event loop.const fs = require('fs'); fs.readFile('file.txt', 'utf8', (err, data) => { if (err) throw err; console.log(data); }); -
HTTP Module:
The
httpmodule allows you to create web servers. Example:
This simple server listens on port 3000 and responds with "Hello, world!"const http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hello, world!'); }); server.listen(3000); -
npm:
Node Package Manager is used to install third-party packages. Dependencies are managed using the
package.jsonfile. Example:npm install express -
Express.js:
A lightweight framework to build APIs and web apps.
This sets up a basic web server with Express.const express = require('express'); const app = express(); app.get('/', (req, res) => res.send('Hello from Express')); app.listen(3000); -
Database Integration:
Node.js connects to databases like MongoDB (NoSQL) and MySQL (SQL). Example using Mongoose:
const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test');
Advanced Concepts
-
Middleware:
Middleware functions in Express handle requests in a pipeline. Example:
This logs each request and passes control to the next middleware or route handler.app.use((req, res, next) => { console.log('Middleware triggered'); next(); }); -
Authentication:
JSON Web Tokens (JWT) are commonly used. Example:
const jwt = require('jsonwebtoken'); const token = jwt.sign({ user: 'admin' }, 'secret'); -
WebSockets:
Real-time communication can be handled with libraries like
socket.io. Example:const io = require('socket.io')(3000); io.on('connection', socket => { socket.on('message', msg => { console.log(msg); }); }); -
Cluster Module:
Improves scalability by utilizing multiple CPU cores.
This allows the Node.js server to spawn workers to handle load.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.writeHead(200); res.end('Handled by worker'); }).listen(8000); }