NODEJS Tutorial
NODEJS Tutorial
JS
I. Introduction
Node.js: A server-side JavaScript runtime that allows you to run JavaScript outside the browser.
It is built on Google Chrome’s V8 JavaScript engine and is excellent at handling asynchronous
operations.
npm (Node Package Manager): A package manager for Node.js that helps you install, manage,
and share JavaScript libraries.
II. Installation
Step 1: Download Node.js
Visit the official website: https://nodejs.org/
Choose the LTS (Long Term Support) version for stability or Current for the latest features.
Download the .msi installer and follow the installation instructions.
Step 2: Verify the installation
After installation, open Command Prompt (cmd) or PowerShell and run:
2. Simple webpage
app.js Command Prompt
const http =
require("http");
const server =
http.createServer((req
, res) => {
res.writeHead(200,
{ "Content-Type":
"text/plain" });
res.write("Hello,
world!");
res.end();
});
server.listen(3000, ()
=> {
console.log("Server is
running at
http://localhost:3000"
);
});
- req (request): Represents the HTTP request sent by the client (browser or another
application).
req.url store url of the request.
For example
http://localhost:3000/ req.url=’/’
http://localhost:3000/home req.url=’/home’
- res (response): Represents the HTTP response that the server sends back to the client.
1. Lightweight and Fast – Express.js is minimal and does not include unnecessary features,
making applications run faster.
2. Middleware Support – Middleware helps process HTTP requests easily, such as
authentication, logging, and error handling.
3. Powerful Routing System – Express allows easy route definitions.
4. Database Integration – Easily connects with databases like MongoDB (using
Mongoose), MySQL, PostgreSQL, etc.
5. Large Community – Many resources and libraries are available on npm.
1. Installing Express.js
First, make sure you have Node.js and npm installed. Then create a folder to hold your
application. Install Express.js with the following command:
Make an express application (compare with the Vanilla Node.js (without Express))
Server.js (use express) Server.js (without express)
const express = require('express'); const http = require("http");
const app = express();
const port = 3000; const server = http.createServer((req, res)
=> {
app.get('/', (req, res) => { res.writeHead(200, { "Content-Type":
res.send('Hello, world!'); "text/plain" });
}); res.write("Hello, world!");
res.end();
app.listen(port, () => { });
console.log(`Server is running at
http://localhost:${port}`); server.listen(3000, () => {
}); console.log("Server is running at
http://localhost:3000");
});
2. Routing
Routing in web development is the process of determining how an application handles HTTP
requests based on the URL. It helps direct users to the correct resources or functionalities on
either the server or the client.
When a user enters a URL, the browser sends a request to the server, which processes it and
returns the appropriate content.
How It Works:
Routing in Express.js is the process of determining how an application handles HTTP requests
based on the URL and HTTP methods (GET, POST, PUT, DELETE, etc.). Express provides a
simple and flexible way to define routes.
Method Description
All_type_routing.js
const express = require("express");
const app = express();
const port = 8000;
// Start server
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
// Start server
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
Post
Put
delete
4. Routing module
When building a large web application with multiple pages and APIs, structuring your routes
properly is essential for maintainability, scalability, and performance. Using Express Router
helps organize routes efficiently instead of keeping everything inside server.js.
module.exports = router;
products.js
const express = require("express");
const router = express.Router();
router.use(express.json()); // Middleware
for parsing JSON
module.exports = router;
Server.js
app.use(express.json()); // Middleware to
parse JSON
// Use routes
app.use("/users", userRoutes);
app.use("/products", productRoutes);
app.use("/orders", orderRoutes);
Note:
- express.Router() is a built-in method in Express.js that creates a modular,
mountable route handler. It helps organize routes into separate files, making the code
cleaner, more scalable, and easier to maintain.
- module.exports: is a special object used to export functions, objects, or variables
from one file so they can be used in another file with require().
Therefore, module.exports = router; will export router variable so that other file
can call require()
- In each file users.js, products.js, orders.js the code
router.get("/", (req, res) => {
res.send("Retrieve product list");
});
We don’t use
router.get("/users", (req, res) => {
res.send("Retrieve product list");
});
Because in servers.js we already use:
app.use("/users", userRoutes);
5. Controller
In larger projects, it's best to separate routing logic from business logic by using controllers.
This makes the code more organized, reusable, and easier to maintain. Instead of defining all
route logic directly in the router file, we move the actual handling logic to separate controller
files.
Using controllers provides several benefits:
✅ Separation of Concerns – Routes handle requests, and controllers handle business logic.
✅ Code Reusability – The same controller function can be used across different routes if needed.
✅ Easier Maintenance – If logic needs to be updated, we modify the controller, not the route
definition.
✅ Better Scalability – Helps manage large projects with multiple features (e.g., users, products,
orders).
// Delete user
exports.deleteUser = (req, res) => {
const { id } = req.params;
res.send(`User with ID ${id} has
been deleted`);
};
router.get("/",
userController.getAllUsers);
router.post("/",
userController.createUser);
router.put("/:id",
userController.updateUser);
router.delete("/:id",
userController.deleteUser);
module.exports = router;
VII. nodemon
nodemon is a tool that automatically restarts a Node.js application when it detects file changes.
It helps developers save time by avoiding the need to manually restart the server after every
code update.
To install nodemon
npm install -g nodemon
to check it has installed
nodemon –v
VIII. Mongoose