NODE.JS

Use Node.js to build fast, scalable server-side applications
with asynchronous JavaScript execution.

Node.js Topics with Explanation and Examples

1. What is Node.js?

Definition: Node.js is an open-source, cross-platform JavaScript runtime environment that executes code outside a browser.

Purpose: Used for building fast, scalable server-side and networking applications.

node app.js
2. Installing Node.js

Download from https://nodejs.org and install.

node -v
npm -v
3. Node.js REPL

REPL stands for Read, Eval, Print, Loop. Used to quickly test JavaScript code.

$ node
> 5 + 6
11
4. Creating First Node.js App

Example of a basic "Hello World" app using Node.js.

const http = require('http');
const server = http.createServer((req, res) => {
  res.end('Hello World');
});
server.listen(3000);
5. Node.js Modules

Modules are reusable blocks of code. Node.js has built-in and custom modules.

const fs = require('fs'); // built-in module
6. Creating Custom Module

You can export and import your own modules.

// calc.js
exports.add = (a, b) => a + b;
7. require() Function

Used to include modules in your file.

const calc = require('./calc');
8. Built-in Module: fs

File System module allows interacting with the file system.

const fs = require('fs');
fs.writeFileSync('file.txt', 'Hello from Node.js');
9. Built-in Module: path

Provides utilities for working with file and directory paths.

const path = require('path');
console.log(path.basename('/test/file.js')); // file.js
10. Built-in Module: os

Provides information about the operating system.

const os = require('os');
console.log(os.platform());
11. npm (Node Package Manager)

Manages external packages and libraries in Node.js projects.

npm install express
12. package.json

Holds metadata about your project and dependencies.

npm init -y
13. Installing Third-party Modules

npm allows installing and managing libraries such as Express, Mongoose, etc.

npm install lodash
14. Creating HTTP Server

Basic server creation using Node's http module.

const http = require('http');
const server = http.createServer((req, res) => {
  res.write('Server is running');
  res.end();
});
server.listen(3000);
15. Event Loop

Core of Node.js that handles asynchronous operations using events and callbacks.

Non-blocking I/O is made possible with the event loop.

16. Events Module

Node.js has a built-in events module to handle events using the EventEmitter class.

const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('start', () => console.log('Started!'));
emitter.emit('start');
17. Callback Functions

Functions passed as arguments to other functions and executed later.

fs.readFile('file.txt', (err, data) => {
  if (err) throw err;
  console.log(data.toString());
});
18. Asynchronous vs Synchronous

Node.js uses asynchronous (non-blocking) I/O by default.

// Sync
const data = fs.readFileSync('file.txt');
// Async
fs.readFile('file.txt', callback);
19. Promises

Modern way to handle asynchronous operations and chaining.

const fetchData = () => Promise.resolve('Done');
fetchData().then(data => console.log(data));
20. Async/Await

Syntactic sugar over promises for cleaner asynchronous code.

async function getData() {
  const result = await fetchData();
  console.log(result);
}
21. Creating JSON APIs

Create APIs that send/receive data in JSON format using Node.js.

res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'Hello' }));
22. Express.js Introduction

Express.js is a fast, unopinionated framework for building web applications in Node.js.

const express = require('express');
const app = express();
app.get('/', (req, res) => res.send('Home Page'));
app.listen(3000);
23. Express Routing

Handles HTTP requests based on URL and method (GET, POST, etc.).

app.get('/about', (req, res) => res.send('About Page'));
24. Express Middleware

Functions that execute during request processing.

app.use((req, res, next) => {
  console.log('Middleware');
  next();
});
25. Handling POST Requests

To handle form or JSON data, use express.json() and express.urlencoded().

app.use(express.json());
app.post('/data', (req, res) => res.send(req.body));
26. Serving Static Files

Use express.static() to serve HTML, CSS, JS files.

app.use(express.static('public'));
27. Environment Variables

Store secrets and configs using process.env and dotenv.

require('dotenv').config();
console.log(process.env.PORT);
28. Creating RESTful APIs

Design pattern for building clean, scalable APIs using CRUD operations.

app.get('/users', ...);
app.post('/users', ...);
app.put('/users/:id', ...);
app.delete('/users/:id', ...);
29. Using Postman

Postman is a GUI tool to test API requests/responses.

Helps to test GET, POST, PUT, DELETE endpoints.

30. Error Handling in Express

Handle errors gracefully using middleware functions with 4 parameters.

app.use((err, req, res, next) => {
  res.status(500).send('Server Error');
});
31. MongoDB with Node.js

MongoDB is a NoSQL database. You can use mongodb or mongoose packages in Node.js to connect.

const { MongoClient } = require('mongodb');
MongoClient.connect('mongodb://localhost:27017', (err, client) => {
  if (err) throw err;
  console.log('Connected!');
});
32. Mongoose ODM

Mongoose is an ODM that simplifies MongoDB interaction using schemas and models.

const mongoose = require('mongoose');
const User = mongoose.model('User', { name: String });
const user = new User({ name: 'John' });
user.save();
33. File Uploads with Multer

multer is a middleware used for handling file uploads.

const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
app.post('/upload', upload.single('file'), (req, res) => {
  res.send('File uploaded');
});
34. Hashing Passwords with bcrypt

bcrypt is used to securely hash passwords before saving.

const bcrypt = require('bcrypt');
const hash = await bcrypt.hash('password123', 10);
35. JSON Web Tokens (JWT)

JWT is used to implement authentication by signing and verifying tokens.

const jwt = require('jsonwebtoken');
const token = jwt.sign({ id: 1 }, 'secretkey');
jwt.verify(token, 'secretkey');
36. CORS in Node.js

cors package enables Cross-Origin Resource Sharing for APIs.

const cors = require('cors');
app.use(cors());
37. Sending Emails with Nodemailer

nodemailer helps in sending emails through Node.js apps.

const nodemailer = require('nodemailer');
const transporter = nodemailer.createTransport({...});
transporter.sendMail({ from: '...', to: '...', text: 'Hello' });
38. Using Template Engines

Template engines like ejs, pug allow dynamic HTML rendering on the server.

app.set('view engine', 'ejs');
app.get('/', (req, res) => res.render('index', { name: 'User' }));
39. Logging with Morgan

morgan is a logger middleware for HTTP request logging.

const morgan = require('morgan');
app.use(morgan('dev'));
40. Global vs Local npm Packages

Global packages are used in CLI across the system. Local are for specific projects.

npm install -g nodemon
npm install express
41. Nodemon for Development

nodemon restarts your Node.js app automatically on code changes.

nodemon app.js
42. Process Object

process is a global object for accessing environment and runtime info.

console.log(process.env.NODE_ENV);
process.exit();
43. Cluster Module

Used to create child processes to handle the load with multiple CPU cores.

const cluster = require('cluster');
if (cluster.isMaster) {
  cluster.fork();
} else {
  console.log('Worker running');
}
44. Deploy Node.js App

Common methods: Heroku, Vercel, Render, or deploying on a VPS with NGINX + PM2.

pm2 start app.js
45. Error Handling Best Practices

Always use try...catch for async/await and proper error logging mechanisms.

try {
  await asyncFunc();
} catch (err) {
  console.error(err.message);
}
46. Streams in Node.js

Streams are used to read or write data in chunks (not all at once).

const fs = require('fs');
const readStream = fs.createReadStream('file.txt');
readStream.on('data', chunk => console.log(chunk.toString()));
47. Buffer in Node.js

Buffers store raw binary data and are useful when dealing with streams.

const buf = Buffer.from('Hello');
console.log(buf.toString()); // Hello
48. Zlib Module

zlib provides compression functionality like Gzip/Deflate.

const zlib = require('zlib');
const input = 'Hello';
zlib.gzip(input, (err, buffer) => console.log(buffer));
49. Child Processes

Use child_process module to spawn subprocesses (run system commands).

const { exec } = require('child_process');
exec('dir', (err, stdout) => console.log(stdout));
50. Path Module

Built-in module to work with file and directory paths.

const path = require('path');
console.log(path.join(__dirname, 'file.txt'));
51. URL Module

Helps parse and format URLs.

const url = require('url');
const parsed = url.parse('http://example.com?name=abc');
console.log(parsed.query);
52. DNS Module

Performs DNS lookups and name resolution.

const dns = require('dns');
dns.lookup('google.com', (err, address) => console.log(address));
53. Net Module (TCP Server)

Used to create low-level TCP servers and clients.

const net = require('net');
const server = net.createServer(socket => socket.write('Hello'));
server.listen(3000);
54. HTTP Status Codes

Status codes like 200, 404, 500 are used in HTTP responses to indicate result of the request.

res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
55. HTTP Headers

Metadata sent with HTTP requests and responses.

res.writeHead(200, { 'Content-Type': 'application/json' });
56. Rate Limiting

Protect APIs from abuse using express-rate-limit.

const rateLimit = require('express-rate-limit');
const limiter = rateLimit({ windowMs: 60000, max: 5 });
app.use(limiter);
57. Helmet for Security

helmet sets HTTP headers to secure your Express app.

const helmet = require('helmet');
app.use(helmet());
58. Session Management

express-session helps maintain user sessions (cookies, server-side).

const session = require('express-session');
app.use(session({ secret: 'key', resave: false, saveUninitialized: true }));
59. Cookie Parser

Middleware for parsing cookies from HTTP requests.

const cookieParser = require('cookie-parser');
app.use(cookieParser());
60. Serving HTML Files

Use Node or Express to send HTML files as a response.

const path = require('path');
app.get('/', (req, res) => res.sendFile(path.join(__dirname, 'index.html')));
Reference Links

Node.js Official Documentation: https://nodejs.org/en/docs

MDN Web Docs (JavaScript / Node concepts): https://developer.mozilla.org/en-US/docs/Web/JavaScript

npm (Package Manager) Documentation: https://docs.npmjs.com/

Express.js Documentation: https://expressjs.com/

Mongoose Documentation: https://mongoosejs.com/docs/

MongoDB Node.js Driver: https://www.mongodb.com/docs/drivers/node/current/

JWT (jsonwebtoken) GitHub: https://github.com/auth0/node-jsonwebtoken

Bcrypt Documentation: https://github.com/kelektiv/node.bcrypt.js/

Nodemailer Docs: https://nodemailer.com/about/

Postman API Testing Tool: https://www.postman.com/

Socket.io (WebSockets with Node.js): https://socket.io/docs/v4/

Helmet Security Middleware: https://helmetjs.github.io/

Express Rate Limit: https://www.npmjs.com/package/express-rate-limit

PM2 (Process Manager for Node.js): https://pm2.keymetrics.io/