What is Node.js?
Node.js is a runtime environment that allows you to run JavaScript outside of the browser — on the server-side.
1. Simple Definition
Node.js lets you use JavaScript to build server-side applications, command-line tools, and backend services.
It’s built on Google Chrome’s V8 JavaScript engine, which makes it fast, efficient, and lightweight.
2. Key Features of Node.js
Feature | Description |
---|---|
🧠 JavaScript Runtime | Runs JS outside the browser |
⚡ Non-blocking I/O | Handles many requests without waiting (asynchronous) |
🧵 Single-threaded | Uses event loop & callbacks for concurrency |
📦 npm | Built-in package manager with 2M+ packages |
💡 Cross-platform | Works on Windows, macOS, Linux |
3. What Can You Build with Node.js?
- Web servers and APIs (REST, GraphQL)
- Real-time apps (chat, live dashboards)
- Command-line tools (CLI utilities)
- Microservices
- Backend logic for web/mobile apps
- File system and automation scripts
4. Basic Node.js Code Example
// hello.js
console.log("Hello from Node.js!");
Run it with:
node hello.js
Output:
Hello from Node.js!
5. Node.js vs Browser JavaScript
Feature Browser JS Node.js
Environment Web browser Server, terminal, backend
Access to DOM ✅ Yes ❌ No
File system access ❌ No ✅ Yes
Modules ES modules or script tags CommonJS (require), ES modules
Purpose UI & frontend behavior Backend, APIs, CLI tools
6. What is npm?
npm = Node Package Manager
It comes with Node.js and lets you install libraries and frameworks.
Example:
npm install express
This installs Express.js, a popular web framework for Node.
7. Why Use Node.js?
- JavaScript everywhere (frontend + backend)
- Fast performance (V8 engine)
- Scalable with event-driven model
- Great for building APIs and real-time apps
- Huge ecosystem with npm packages
Node.js REPL – Read Eval Print Loop
REPL stands for Read-Eval-Print Loop.
It’s an interactive environment that comes with Node.js where you can:
- Type JavaScript code
- Execute it immediately
- See the result instantly
1. What is REPL?
REPL is like a JavaScript playground in your terminal.
It allows you to experiment with code, test logic, and explore Node.js features in real time.
2. How to Start the Node REPL
Open your terminal and type:
node
Working with Files in Node.js
Node.js provides the built-in fs
(File System) module to let you read, write, update, and delete files directly from your code.
The process
Object in Node.js
In Node.js, the global process
object provides information and control over the current Node.js process.
1. What is process
?
The
process
object is a built-in global object in Node.js.
It provides methods and properties to interact with the system, handle input/output, and control execution flow.
2. Accessing Command Line Arguments
console.log(process.argv);
process.argv is an array containing:
- The Node executable path
- The script file path
- Any additional arguments
Example:
node app.js hello world
Output:
[
'/usr/bin/node',
'/path/to/app.js',
'hello',
'world'
]
You can access them like:
const args = process.argv.slice(2);
console.log("User input:", args);
Exporting in Node.js Files
In Node.js, modular programming is achieved using the CommonJS module system, which allows you to export and import code between files.
1. Why Use exports
?
- Organize code into smaller reusable files
- Share functions, variables, classes, or objects
- Keep your codebase clean and maintainable
2. Basic Export with module.exports
math.js
(export file)
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
module.exports = {
add,
subtract
};
app.js (import file)
const math = require('./math');
console.log(math.add(5, 3)); // 8
console.log(math.subtract(10, 4)); // 6
Exporting from Directories in Node.js
In Node.js, when you organize code across multiple files inside a folder, you can simplify importing by exporting from the directory itself using an index.js
file.
1. Why Export from a Directory?
- Group related modules (e.g.,
User
,Auth
,Utils
) - Avoid long import paths
- Simplify the import statement with a single entry point
2. Directory Structure Example
/utils
├── add.js
├── subtract.js
└── index.js
add.js
function add(a, b) {
return a + b;
}
module.exports = add;
subtract.js
function subtract(a, b) {
return a - b;
}
module.exports = subtract;
index.js (in /utils folder)
const add = require('./add');
const subtract = require('./subtract');
module.exports = {
add,
subtract
};
3. Importing from the Directory
const utils = require('./utils');
console.log(utils.add(5, 3)); // 8
console.log(utils.subtract(10, 4)); // 6
Node will automatically look for index.js when you require('./folder').
What is npm?
npm stands for Node Package Manager.
It is the default package manager for Node.js, used to:
- Install libraries and tools
- Manage dependencies
- Publish your own packages
1. Key Facts About npm
Feature | Description |
---|---|
🧠 Name | Node Package Manager |
📂 Comes With | Node.js installation (node -v , npm -v ) |
🌍 Registry | https://www.npmjs.com (over 2 million packages) |
📦 File Used |
package.json to manage project dependencies |
📥 Install Packages | npm install <package-name> |
📤 Publish Package | npm publish |
2. Installing a Package
In Node.js, you can install external libraries (packages) using npm (Node Package Manager).
npm install <package-name>
- Adds it to the node_modules folder.
- Adds it to dependencies in package.json (if --save or default).
Understanding package.json
in Node.js
The package.json
file is the heart of any Node.js project.
It stores metadata about the project and manages its dependencies, scripts, and configuration.
1. Why package.json
Matters
- 📂 Describes your project (name, version, author, license)
- 📦 Tracks installed packages (dependencies & devDependencies)
- ⚙️ Defines scripts for tasks (start, test, build)
- 🧩 Required to publish a package to npm
2. How to Create package.json
npm init
3. Example package.json
{
"name": "my-app",
"version": "1.0.0",
"description": "A sample Node.js project",
"main": "index.js",
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js",
"test": "echo \"No tests yet\""
},
"author": "Bhupesh Kumar",
"license": "MIT",
"dependencies": {
"express": "^4.18.2"
},
"devDependencies": {
"nodemon": "^2.0.22"
}
}
Local vs Global Installation in npm
When installing packages with npm
, you can choose between:
- Local Installation: For a specific project
- Global Installation: Available system-wide (all projects)
Local Installation
Command:
npm install <package-name>
Example:
npm install express
Where It Goes:
- Installed inside the project’s node_modules/ folder
- Listed in package.json under "dependencies" or "devDependencies"
Use When:
- The package is only needed for a specific project
- You want different versions in different projects
Global Installation
Command:
npm install -g <package-name>
Example:
npm install -g nodemon
Where It Goes:
- Installed in a system-wide folder
- Can be run from any terminal, any directory
Use When:
- Package is a command-line tool (e.g., nodemon, http-server, eslint)
- You want it available globally
Checking Install Type
List global packages:
npm list -g --depth=0
List local project packages:
npm list --depth=0
Importing Modules in Node.js
Node.js follows a modular architecture, where you can import and reuse code across files using the require()
function or the modern import
statement (ES Modules).
1. CommonJS Syntax (require
)
Importing a File:
const math = require('./math');
2. ES Module Syntax (import)
Use this syntax when "type": "module" is set in package.json.
Import Default Export:
import express from 'express';
Import Named Export:
import { add, subtract } from './math.js';
Import Everything:
import * as utils from './utils.js';
What is Express.js?
Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for building web applications and APIs.
It simplifies the process of handling routes, requests, middleware, and server logic in Node.js.
1. Why Use Express?
Feature | Benefit |
---|---|
🧩 Middleware support | Add custom functionality easily |
📦 Routing system | Handle URL endpoints with clean syntax |
⚙️ Simplified server setup | No need to write verbose Node.js HTTP code |
🌐 REST API building | Perfect for backend APIs and microservices |
🛠 Integrations | Easily integrates with MongoDB, MySQL, templating engines |
2. Installing Express
npm install express
3. Basic Express Server
const express = require('express');
const app = express();
// Route
app.get('/', (req, res) => {
res.send('Hello from Express!');
});
// Start server
app.listen(3000, () => {
console.log('🚀 Server running on http://localhost:3000');
});
Library vs Framework in JavaScript
Understanding the difference between a library and a framework is essential for every developer. They both help you write better code, but they do so in different ways.
1. Definition
Concept | Description |
---|---|
📚 Library | A collection of reusable functions or modules that you call as needed. |
🏗 Framework | A structured platform that dictates the architecture and flow of your app. |
2. Control Flow: Inversion of Control
This is the main difference:
Feature | Library | Framework |
---|---|---|
Who’s in charge? | You call the library code | Framework calls your code |
Control Flow | You remain in control | Framework is in control |
3. Examples
Library | Description |
---|---|
Lodash | Utility functions for arrays, objects, etc. |
Axios | HTTP request library |
jQuery | DOM manipulation library |
Framework | Description |
---|---|
Express.js | Web framework for Node.js |
Angular | Full-fledged frontend framework |
Next.js | Framework for React apps |
4. Real-life Analogy
A library is like ordering à la carte at a restaurant — you choose what you want and when.
A framework is like a fixed menu — it decides the courses and when you get them.
5. Summary Table
Feature | Library | Framework |
---|---|---|
Control | You call the code | It calls your code |
Flexibility | High | Less, follows set structure |
Learning curve | Generally lower | Can be higher |
Examples | Lodash, Axios, jQuery | Express, Angular, Next.js |
Final Thoughts
- Use a library when you need specific functionality without strict rules.
- Use a framework when you need a complete structure and guidelines for building your app.
✨ “Libraries are helpers. Frameworks are architects.”
Handling Requests in Express.js
Express.js makes it easy to handle different types of HTTP requests (GET
, POST
, PUT
, DELETE
, etc.) using intuitive routing methods.
1. Basic Structure of a Route
app.METHOD(PATH, HANDLER)
Sending a Response in Express.js
In Express.js, you use the res
(response) object to send data back to the client.
This response could be text, HTML, JSON, status codes, or redirects.
1. res.send()
Sends a plain text or HTML response.
app.get('/', (req, res) => {
res.send('Hello from Express!');
});
Routing in Express.js
Routing in Express refers to how an application responds to client requests for a particular endpoint (URI + HTTP method).
1. Basic Route Syntax
app.METHOD(PATH, HANDLER)
- METHOD: HTTP verb like GET, POST, etc.
- PATH: Route path
- HANDLER: Callback function (req, res)
2. Example Routes
app.get('/', (req, res) => {
res.send('Home Page');
});
app.post('/submit', (req, res) => {
res.send('Form Submitted');
});
app.put('/update', (req, res) => {
res.send('Update Successful');
});
app.delete('/delete', (req, res) => {
res.send('Deleted Successfully');
});
3. Route Parameters
Used to capture values from the URL.
app.get('/users/:id', (req, res) => {
res.send(`User ID: ${req.params.id}`);
});
4. Query Parameters
Used to pass optional key-value pairs in the URL.
app.get('/search', (req, res) => {
res.send(`You searched for: ${req.query.q}`);
});
URL Example: /search?q=express
5. Multiple Handlers
app.get('/demo',
(req, res, next) => {
console.log('Middleware 1');
next();
},
(req, res) => {
res.send('Final Response');
}
);
Installing and Using Nodemon in Node.js
Nodemon is a utility that automatically restarts your Node.js application whenever file changes are detected. It boosts productivity during development.
1. What is Nodemon?
- Monitors your project files.
- Automatically restarts the server on save.
- Ideal for development (not used in production).
2. Installing Nodemon
Local Installation (recommended)
npm install --save-dev nodemon
Path Parameters in Express.js
Path parameters (also called route parameters) allow you to capture dynamic values from the URL path and use them inside your route handler.
1. What are Path Parameters?
Path parameters are defined using a colon (:
) followed by a name in the route path.
They are useful for handling dynamic URLs, such as /users/123
or /products/456
.
2. Basic Syntax
app.get('/users/:id', (req, res) => {
const userId = req.params.id;
res.send(`User ID is: ${userId}`);
});
Query Strings in Express.js
Query strings are key-value pairs added to the end of a URL to send optional parameters to the server.
They appear after a ?
and are separated by &
.
1. What is a Query String?
URL Example: http://localhost:3000/search?term=express&limit=10
Here:
-
term
=express
-
limit
=10
2. Accessing Query Strings in Express
Use the req.query
object to access query string parameters.
Example:
app.get('/search', (req, res) => {
const { term, limit } = req.query;
res.send(`Search Term: ${term}, Limit: ${limit}`);
});
If user visits:
http://localhost:3000/search?term=express&limit=5
Output:
Search Term: express, Limit: 5
Templating in Express.js
Templating allows you to generate dynamic HTML pages in Express by embedding server-side data into frontend code using template engines.
1. What is a Template Engine?
A template engine enables you to render dynamic content on the server before sending it to the client.
Popular engines include:
- EJS (Embedded JavaScript)
- Pug (formerly Jade)
- Handlebars
2. Installing a Template Engine (Example: EJS)
EJS (Embedded JavaScript Templates) is a simple templating language that lets you generate HTML markup with plain JavaScript.
npm install ejs
3. Setting Up EJS with Express
const express = require('express');
const app = express();
// Set EJS as the template engine
app.set('view engine', 'ejs');
// Optional: set views folder
app.set('views', './views');
4. Creating a View File
Create a file: views/home.ejs
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
</head>
<body>
<h1>Hello, <%= user %>!</h1>
</body>
</html>
5. Rendering the View
app.get('/', (req, res) => {
res.render('home', {
title: 'Welcome Page',
user: 'Bhupesh'
});
});
Output HTML sent to browser:
<h1>Hello, Bhupesh!</h1>
Views Directory in Express.js
In Express.js, the views directory is where your template (view) files are stored when using a templating engine like EJS, Pug, or Handlebars.
1. Default Views Directory
By default, Express looks for views in a folder named views
in the project root.
2. Customizing the Views Directory
You can change the default views folder using:
app.set('views', './templates');
Interpolation Syntax in EJS
Interpolation in EJS (Embedded JavaScript) allows you to embed dynamic data into your HTML templates. This makes it easy to render server-side data directly in your views.
1. Basic Interpolation
<h1>Hello, <%= name %>!</h1>
- <%= %> outputs the value of a variable with HTML escaping.
- Useful for injecting safe, dynamic content.
Example:
res.render('home', { name: 'Bhupesh' });
Rendered HTML:
<h1>Hello, Bhupesh!</h1>
Syntax | Purpose |
---|---|
<%= %> |
Output with HTML escaping |
<%- %> |
Output without escaping (raw HTML) |
<% %> |
JavaScript logic (no output) |
Passing Data to EJS Templates in Express.js
When using EJS as your view engine, you can easily pass data from your Express routes to the EJS template for dynamic rendering.
1. Basic Syntax
res.render('templateName', dataObject);
2. Example
Route (Express)
app.get('/', (req, res) => {
res.render('home', { username: 'Bhupesh', loggedIn: true });
});
Template (views/home.ejs)
<h1>Welcome, <%= username %>!</h1>
<% if (loggedIn) { %>
<p>You are logged in.</p>
<% } else { %>
<p>Please log in to continue.</p>
<% } %>
Output in browser:
Welcome, Bhupesh!
You are logged in.
Concept | Syntax/Usage |
---|---|
Basic | res.render('view', { key: value }) |
Access in EJS | <%= key %> |
Arrays/Objects | Loop through with <% %>
|
Conditional Logic | <% if (...) { %> |
Conditional Statements in EJS
EJS (Embedded JavaScript) allows you to write JavaScript logic directly in your HTML templates using special tags.
1. Basic if
Statement
<% if (user) { %>
<h2>Welcome, <%= user %>!</h2>
<% } %>
Syntax | Purpose |
---|---|
<% if () { %> |
Run JavaScript conditionally |
<% } else { %> |
Alternative block |
<%= %> |
Output escaped value |
<%- %> |
Output unescaped (raw HTML) value |
Loops in EJS
EJS allows you to use JavaScript loops to dynamically render lists, tables, and repeated elements in your HTML.
1. forEach
Loop
Commonly used to iterate over arrays in EJS templates.
<ul>
<% items.forEach(item => { %>
<li><%= item %></li>
<% }) %>
</ul>
- Classic for Loop
You can use a standard JavaScript for loop too:
<ul>
<% for(let i = 0; i < items.length; i++) { %>
<li><%= items[i] %></li>
<% } %>
</ul>
Feature | Syntax Example |
---|---|
forEach loop |
<% items.forEach(item => { %> |
Classic for loop |
<% for (let i = 0; i < n; i++) { %> |
Output value | <%= item %> |
JS logic only | <% %> |
Serving Static Files in EJS with Express
To use images, CSS, JS, or other static assets in your EJS templates, Express provides a built-in way to serve static files using express.static()
.
1. Set Up the Static Directory
Create a folder named public
(or any name you prefer):
project/
├── public/
│ ├── css/
│ │ └── style.css
│ ├── js/
│ │ └── script.js
│ └── images/
│ └── logo.png
├── views/
│ └── home.ejs
├── index.js
└── package.json
✅ 2. Serve Static Files with Express
In your index.js
or app.js
:
const express = require('express');
const app = express();
// Serve static files from the "public" directory
app.use(express.static('public'));
app.set('view engine', 'ejs');
app.set('views', './views');
app.get('/', (req, res) => {
res.render('home');
});
3. Use Static Files in EJS
Linking a CSS File
<!-- views/home.ejs -->
<link rel="stylesheet" href="/css/style.css">
Adding a JS File
<script src="/js/script.js"></script>
Using an Image
<img src="/images/logo.png" alt="Logo">
EJS Includes
EJS supports file inclusion using the <%- include() %>
syntax. This allows you to reuse common components like headers, footers, navbars, etc., across multiple pages.
1. Basic Syntax
<%- include('filename') %>
2. Example Folder Structure
project/
├── views/
│ ├── partials/
│ │ ├── header.ejs
│ │ └── footer.ejs
│ ├── pages/
│ │ └── home.ejs
│ └── layout.ejs
├── index.js
3. Using Partials in a Page
pages/home.ejs
<%- include('../partials/header') %>
<h2>Welcome to the Home Page</h2>
<p>This is dynamic content for the homepage.</p>
<%- include('../partials/footer') %>
GET and POST Requests in Express.js
Express.js supports different types of HTTP requests, with GET and POST being the most commonly used.
1. GET Request
Used to retrieve data from the server. Typically triggered by clicking a link or visiting a URL.
Route Definition:
app.get('/greet', (req, res) => {
res.send('Hello from GET!');
});
Access Query Parameters:
// URL: /search?term=express
app.get('/search', (req, res) => {
const { term } = req.query;
res.send(`You searched for: ${term}`);
});
2. POST Request
Used to send data to the server, often from forms.
You must use express.urlencoded() middleware to parse form data.
Enable Form Data Parsing:
app.use(express.urlencoded({ extended: true }));
Route Definition:
app.post('/submit', (req, res) => {
const { name } = req.body;
res.send(`Form submitted by ${name}`);
});
HTML Form Example (EJS):
<form action="/submit" method="POST">
<input type="text" name="name" placeholder="Enter your name" />
<button type="submit">Submit</button>
</form>
Handling POST Requests in Express.js
A POST request is used to send data from the client to the server. It is commonly used in form submissions and APIs.
1. Enabling Body Parsing
To read form data or JSON from req.body
, use the following middlewares:
const express = require('express');
const app = express();
// Middleware to parse URL-encoded form data
app.use(express.urlencoded({ extended: true }));
// Middleware to parse JSON data
app.use(express.json());
2. Basic POST Route
app.post('/submit', (req, res) => {
const { name, email } = req.body;
res.send(`Received: ${name}, ${email}`);
});
3. Example Form (HTML or EJS)
<form action="/submit" method="POST">
<input type="text" name="name" placeholder="Enter your name" />
<input type="email" name="email" placeholder="Enter your email" />
<button type="submit">Submit</button>
</form>
What is REST?
REST stands for Representational State Transfer. It is a software architectural style used to design scalable, stateless, and cacheable web services.
Key Concepts of REST:
-
Client-Server Architecture
- Separation of concerns: client (frontend) handles UI, server (backend) handles data and logic.
-
Stateless
- Each request from the client contains all the information needed to process the request.
- The server does not remember any client context between requests.
-
Cacheable
- Responses must explicitly indicate if they are cacheable or not to improve performance.
-
Uniform Interface
- A consistent way of interacting with resources using standard HTTP methods:
-
GET
: Retrieve data -
POST
: Create data -
PUT
: Update data -
DELETE
: Remove data
-
- A consistent way of interacting with resources using standard HTTP methods:
-
Layered System
- Architecture composed of hierarchical layers, allowing load balancers, security layers, etc.
-
Resource-Based
- Everything is considered a resource (e.g., users, posts, products).
- Resources are identified using URIs (Uniform Resource Identifiers).
Example of RESTful API:
- GET /users → Get all users
- GET /users/5 → Get user with ID 5
- POST /users → Create a new user
- PUT /users/5 → Update user with ID 5
- DELETE /users/5 → Delete user with ID 5
REST vs RESTful
- REST is the architectural style.
- RESTful APIs are web services that follow the REST principles.
Summary
Term | Meaning |
---|---|
REST | Design principle for APIs |
Stateless | No session data stored on server |
Resource | Data like users, posts, etc. accessed via URI |
HTTP Methods | GET, POST, PUT, DELETE, etc. |
CRUD Operations in Web Development
CRUD stands for the four basic types of operations you can perform on persistent data in most applications:
Create | Read | Update | Delete
These operations are the foundation of working with databases, APIs, and RESTful services.
1. Create (POST)
Used to add new data to a database or resource.
Example (REST API):
POST /users
Sample Request Body:
{
"name": "Bhupesh",
"email": "bhupesh@example.com"
}
2. Read (GET)
Used to retrieve data from the server.
GET /users // Get all users
GET /users/123 // Get user with ID 123
3. Update (PUT / PATCH)
Used to modify existing data.
- PUT: Replaces the entire resource
- PATCH: Updates part of the resource
PUT /users/123
Sample Request Body:
{
"name": "Bhupesh Kumar",
"email": "bhupesh@example.com"
}
4. Delete (DELETE)
Used to remove data from the server.
Example:
DELETE /users/123
Creating RESTful APIs with Express.js
A RESTful API uses HTTP methods to perform CRUD operations on resources. Express.js makes it easy to build these APIs in Node.js.
Step 1: Setup
1. Initialize Project
npm init -y
npm install express
2. Create app.js
const express = require('express');
const app = express();
const PORT = 3000;
app.use(express.json()); // Middleware to parse JSON
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Step 2: Define In-Memory Data
let users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bhupesh" }
];
Step 3: Create RESTful Routes
1. GET All Users
app.get('/users', (req, res) => {
res.json(users);
});
2. GET User by ID
app.get('/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
user ? res.json(user) : res.status(404).send("User not found");
});
3. POST Create New User
app.post('/users', (req, res) => {
const newUser = {
id: users.length + 1,
name: req.body.name
};
users.push(newUser);
res.status(201).json(newUser);
});
4. PUT Update User
app.put('/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (user) {
user.name = req.body.name;
res.json(user);
} else {
res.status(404).send("User not found");
}
});
5. DELETE User
app.delete('/users/:id', (req, res) => {
users = users.filter(u => u.id !== parseInt(req.params.id));
res.send("User deleted");
});
Index Route in RESTful APIs
What is an Index Route?
The index route is the endpoint that returns a list of all resources of a particular type.
It usually responds to a GET request at the root of a resource path.
Create and New Routes in RESTful APIs
In a RESTful API, "Create" and "New" routes are used to add new resources to a collection.
1. New Route
The New route is used to display a form (typically in server-rendered apps) to collect data for creating a new resource.
🚫 Not commonly used in API-only backends — more relevant for apps using templating engines like EJS or Pug.
Route Pattern:
GET /users/new
Redirects in Express.js
In Express.js, the res.redirect()
method is used to redirect the client to a different URL.
Syntax
res.redirect([statusCode], path)
Example
app.get('/', (req, res) => {
res.send('Welcome to the homepage!');
});
app.get('/home', (req, res) => {
res.redirect('/'); // Redirect to homepage
});
Show Route in RESTful APIs
The Show Route is used to retrieve and display a single resource based on its unique identifier (usually an id
).
Purpose
- Fetch details of a specific item
- Common in detail views (e.g., user profile, blog post, product page)
URL Pattern
GET /resources/:id
Example
app.get('/users/:id', (req, res) => {
const userId = parseInt(req.params.id);
const user = users.find(u => u.id === userId);
if (user) {
res.json(user);
} else {
res.status(404).send("User not found");
}
});
Creating Unique IDs for Posts using UUID in Express.js
To uniquely identify each post or record in your API, you can use UUIDs (Universally Unique Identifiers) instead of simple numeric IDs.
Why Use UUID?
- Universally unique across systems
- Safer than incremental IDs
- Great for distributed applications
Step 1: Install UUID Library
npm install uuid
Step 2: Import and Use UUID
const express = require('express');
const { v4: uuidv4 } = require('uuid');
const app = express();
app.use(express.json());
let posts = [];
Step 3: Create a Post with UUID
app.post('/posts', (req, res) => {
const newPost = {
id: uuidv4(),
title: req.body.title,
content: req.body.content
};
posts.push(newPost);
res.status(201).json(newPost);
});
Step 4: Show a Post by UUID
app.get('/posts/:id', (req, res) => {
const post = posts.find(p => p.id === req.params.id);
if (post) {
res.json(post);
} else {
res.status(404).json({ message: "Post not found" });
}
});
Example Output
{
"id": "a12f4a1b-9f34-432a-b23d-8dfd0fe7a239",
"title": "My First Post",
"content": "This is my first post using UUID!"
}
Update Route in RESTful APIs
The Update Route allows you to modify an existing resource. It uses either the PUT
or PATCH
HTTP method.
When to Use PUT vs PATCH
Method | Description |
---|---|
PUT |
Replaces the entire resource |
PATCH |
Updates part of the resource (partial) |
URL Pattern
PUT /posts/:id
PATCH /posts/:id
Example in Express.js
Assume we are working with an array of posts:
let posts = [
{ id: "1", title: "Old Title", content: "Old content" }
];
PUT Example (Full Update)
app.put('/posts/:id', (req, res) => {
const post = posts.find(p => p.id === req.params.id);
if (post) {
post.title = req.body.title;
post.content = req.body.content;
res.json(post);
} else {
res.status(404).json({ message: "Post not found" });
}
});
PATCH Example (Partial Update)
app.patch('/posts/:id', (req, res) => {
const post = posts.find(p => p.id === req.params.id);
if (post) {
if (req.body.title) post.title = req.body.title;
if (req.body.content) post.content = req.body.content;
res.json(post);
} else {
res.status(404).json({ message: "Post not found" });
}
});
Sample Request Body (for PUT)
{
"title": "Updated Title",
"content": "Updated content goes here"
}
Edit Route in RESTful APIs
The Edit Route is typically used in server-rendered applications (like those using EJS or Pug) to display a form pre-filled with existing data, allowing a user to make changes to a resource.
⚠️ Note: This is different from the Update Route, which actually performs the data update.
Purpose
- Render a form to edit a resource (like a post or user)
- Pre-populate form fields with current data
URL Pattern
GET /posts/:id/edit
Example in Express.js with EJS
app.get('/posts/:id/edit', (req, res) => {
const post = posts.find(p => p.id === req.params.id);
if (post) {
res.render('editPost', { post });
} else {
res.status(404).send("Post not found");
}
});
Sample EJS Template (editPost.ejs)
<h1>Edit Post</h1>
<form action="/posts/<%= post.id %>?_method=PUT" method="POST">
<input type="text" name="title" value="<%= post.title %>" required />
<textarea name="content"><%= post.content %></textarea>
<button type="submit">Update</button>
</form>
- Make sure to use middleware like method-override to support PUT/DELETE via forms.
Destroy Route in RESTful APIs
The Destroy Route allows you to delete a specific resource from the server/database. It uses the DELETE
HTTP method.
Purpose
- Permanently remove an item (e.g., post, user, product)
- Triggered by user action (e.g., clicking a delete button)
URL Pattern
DELETE /posts/:id
Example in Express.js
Assume an in-memory posts array:
let posts = [
{ id: "1", title: "Post 1" },
{ id: "2", title: "Post 2" }
];
Destroy Route
app.delete('/posts/:id', (req, res) => {
const postId = req.params.id;
const postIndex = posts.findIndex(p => p.id === postId);
if (postIndex !== -1) {
posts.splice(postIndex, 1);
res.send(`Post ${postId} deleted`);
} else {
res.status(404).send("Post not found");
}
});
- If using an HTML form to trigger this, you'll need method-override.
That's a Wrap for Part 1!
We’ve officially wrapped up Part 1 of our backend journey, covering:
- 🌐 Node.js fundamentals and REPL
- 📦 npm, modules, and project structure
- 🚀 Express.js for building web servers
- 📄 EJS templating for dynamic content
- 🛠️ RESTful routing (Index, Show, Create, Edit, Update, Destroy)
Whether you're building APIs or full-stack web apps, these core concepts are the foundation for becoming a strong backend developer.
🧠 Tip: Keep experimenting with small projects as you go. It’s the best way to learn!
📢 Stay tuned for Part 2, where we dive deeper into backend magic with databases, authentication, and more real-world features! 🔥
💬 Got feedback or suggestions? Drop a comment and let’s grow together.
🚀 Happy Coding!
Top comments (1)
there is a CLI named BeB you can use it to create a backend experss and mongodb project in one line try it 😁