Use Node.js to build fast, scalable server-side applications
with asynchronous JavaScript execution.
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
Download from https://nodejs.org and install.
node -v
npm -v
REPL stands for Read, Eval, Print, Loop. Used to quickly test JavaScript code.
$ node
> 5 + 6
11
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);
Modules are reusable blocks of code. Node.js has built-in and custom modules.
const fs = require('fs'); // built-in module
You can export and import your own modules.
// calc.js
exports.add = (a, b) => a + b;
Used to include modules in your file.
const calc = require('./calc');
File System module allows interacting with the file system.
const fs = require('fs');
fs.writeFileSync('file.txt', 'Hello from Node.js');
Provides utilities for working with file and directory paths.
const path = require('path');
console.log(path.basename('/test/file.js')); // file.js
Provides information about the operating system.
const os = require('os');
console.log(os.platform());
Manages external packages and libraries in Node.js projects.
npm install express
Holds metadata about your project and dependencies.
npm init -y
npm allows installing and managing libraries such as Express, Mongoose, etc.
npm install lodash
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);
Core of Node.js that handles asynchronous operations using events and callbacks.
Non-blocking I/O is made possible with the event loop.
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');
Functions passed as arguments to other functions and executed later.
fs.readFile('file.txt', (err, data) => {
if (err) throw err;
console.log(data.toString());
});
Node.js uses asynchronous (non-blocking) I/O by default.
// Sync
const data = fs.readFileSync('file.txt');
// Async
fs.readFile('file.txt', callback);
Modern way to handle asynchronous operations and chaining.
const fetchData = () => Promise.resolve('Done');
fetchData().then(data => console.log(data));
Syntactic sugar over promises for cleaner asynchronous code.
async function getData() {
const result = await fetchData();
console.log(result);
}
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' }));
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);
Handles HTTP requests based on URL and method (GET, POST, etc.).
app.get('/about', (req, res) => res.send('About Page'));
Functions that execute during request processing.
app.use((req, res, next) => {
console.log('Middleware');
next();
});
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));
Use express.static()
to serve HTML, CSS, JS files.
app.use(express.static('public'));
Store secrets and configs using process.env
and dotenv
.
require('dotenv').config();
console.log(process.env.PORT);
Design pattern for building clean, scalable APIs using CRUD operations.
app.get('/users', ...);
app.post('/users', ...);
app.put('/users/:id', ...);
app.delete('/users/:id', ...);
Postman is a GUI tool to test API requests/responses.
Helps to test GET, POST, PUT, DELETE endpoints.
Handle errors gracefully using middleware functions with 4 parameters.
app.use((err, req, res, next) => {
res.status(500).send('Server Error');
});
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!');
});
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();
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');
});
bcrypt
is used to securely hash passwords before saving.
const bcrypt = require('bcrypt');
const hash = await bcrypt.hash('password123', 10);
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');
cors
package enables Cross-Origin Resource Sharing for APIs.
const cors = require('cors');
app.use(cors());
nodemailer
helps in sending emails through Node.js apps.
const nodemailer = require('nodemailer');
const transporter = nodemailer.createTransport({...});
transporter.sendMail({ from: '...', to: '...', text: 'Hello' });
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' }));
morgan
is a logger middleware for HTTP request logging.
const morgan = require('morgan');
app.use(morgan('dev'));
Global packages are used in CLI across the system. Local are for specific projects.
npm install -g nodemon
npm install express
nodemon
restarts your Node.js app automatically on code changes.
nodemon app.js
process
is a global object for accessing environment and runtime info.
console.log(process.env.NODE_ENV);
process.exit();
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');
}
Common methods: Heroku, Vercel, Render, or deploying on a VPS with NGINX + PM2.
pm2 start app.js
Always use try...catch
for async/await and proper error logging mechanisms.
try {
await asyncFunc();
} catch (err) {
console.error(err.message);
}
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()));
Buffers store raw binary data and are useful when dealing with streams.
const buf = Buffer.from('Hello');
console.log(buf.toString()); // Hello
zlib
provides compression functionality like Gzip/Deflate.
const zlib = require('zlib');
const input = 'Hello';
zlib.gzip(input, (err, buffer) => console.log(buffer));
Use child_process
module to spawn subprocesses (run system commands).
const { exec } = require('child_process');
exec('dir', (err, stdout) => console.log(stdout));
Built-in module to work with file and directory paths.
const path = require('path');
console.log(path.join(__dirname, 'file.txt'));
Helps parse and format URLs.
const url = require('url');
const parsed = url.parse('http://example.com?name=abc');
console.log(parsed.query);
Performs DNS lookups and name resolution.
const dns = require('dns');
dns.lookup('google.com', (err, address) => console.log(address));
Used to create low-level TCP servers and clients.
const net = require('net');
const server = net.createServer(socket => socket.write('Hello'));
server.listen(3000);
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');
Metadata sent with HTTP requests and responses.
res.writeHead(200, { 'Content-Type': 'application/json' });
Protect APIs from abuse using express-rate-limit
.
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({ windowMs: 60000, max: 5 });
app.use(limiter);
helmet
sets HTTP headers to secure your Express app.
const helmet = require('helmet');
app.use(helmet());
express-session
helps maintain user sessions (cookies, server-side).
const session = require('express-session');
app.use(session({ secret: 'key', resave: false, saveUninitialized: true }));
Middleware for parsing cookies from HTTP requests.
const cookieParser = require('cookie-parser');
app.use(cookieParser());
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')));
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/