0% found this document useful (0 votes)
1 views16 pages

NODEJS Tutorial

Node.js is a server-side JavaScript runtime built on Google Chrome’s V8 engine, designed for handling asynchronous operations. The document covers installation, basic commands, project setup, and the use of Express.js for web applications, including routing and middleware. It emphasizes the importance of the package.json file for managing project dependencies and configurations.

Uploaded by

haultgcc220122
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views16 pages

NODEJS Tutorial

Node.js is a server-side JavaScript runtime built on Google Chrome’s V8 engine, designed for handling asynchronous operations. The document covers installation, basic commands, project setup, and the use of Express.js for web applications, including routing and middleware. It emphasizes the importance of the package.json file for managing project dependencies and configurations.

Uploaded by

haultgcc220122
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

NODE.

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:

III. Basic Commands


node
Function Description Example
node <js file> Start a js file node app.js
node -v Check Node.js version
Ctrl + C Exit REPL mode
npm
npm init -y creates a package.json file
with default settings.
package.json is a crucial file in
a Node.js project. It contains
information about the project,
including dependencies
(required libraries), scripts to
run the project, and various
configurations.
{
"name": "my-app",
"version": "1.0.0",
"description": "",
"scripts": {
"test": "echo \"Error: no test
specified\" && exit 1"
},
"dependencies": {},
"devDependencies": {}
}
npm install <package-name> Install a package npm install express
Installing Express.js (a web
framework)
npm uninstall <package- Uninstall a package npm uninstall express
name>
npm run <script-name> Run a script from package.json npm run start # Starts the
Example server normally npm run
"scripts": { dev # Starts the server with
"start": "node server.js", nodemon
"dev": "nodemon server.js"
}

IV. Start project


1. Simple console app
Create a folder. Create a file app.js
app.js Command Prompt
console.log("Hello
Node.js!");

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"
);
});

 const http = require("http");


This line imports the built-in http module in Node.js, which is used to create an HTTP server.
The http variable now contains all the necessary methods to create and manage the server.
 const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Hello, world!");
});
The http.createServer() function creates a new HTTP server.
It takes a callback function with two parameters:

- 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.

An aside => Arrow functions


Arrow functions are one of the features introduced in the ES6 version of JavaScript. It allows
you to create functions in a cleaner way compared to regular functions. For example:

Arrow function syntax

- myFunction is the name of the function


- arg1, arg2, ...argN are the function arguments
- statement(s) is the function body
If the body has single statement or expression, you can write arrow function as:
 res.writeHead(200, { "Content-Type": "text/plain" });
- Sends an HTTP status code 200, meaning the request was successful.
- Sets the header "Content-Type": "text/plain", meaning the response will be in plain
text format.
res.write("Hello, world!");
- Sends the response "Hello, world!" to the client.
 res.end();
- Ends the response.

Exercise: Work on tutorial9


V. package.json and package-lock.json
1. package.json is a crucial file in a Node.js project. It contains information about the
project, including dependencies (required libraries), scripts to run the project, and
various configurations. The package.json file is essential in any Node.js project
because it serves as a blueprint for the project.
- Dependency Management: When developing a Node.js application, you often use
external libraries (dependencies) like Express, Mongoose, or Axios. Therefore,
package.json keeps track of all installed packages and their versions. Without
package.json, you would have to manually remember and install all the dependencies.
- Project Metadata and Configuration: package.json contains important details about
the project, such as: Project name (name), Version (version), Author information
(author), License (license), Entry point file (main)
- Automating Tasks with npm Scripts: package.json allows you to define custom scripts
to automate repetitive tasks like: Starting the server Running tests Linting code
"scripts": { "start": "node server.js", "dev": "nodemon server.js", "test": "jest" }
npm run start # Runs `node server.js`
npm run dev # Runs `nodemon server.js`
npm run test # Runs Jest for testing
2. Structure of package.json
{
"name": "my-app",
"version": "1.0.0",
"description": "A simple Node.js app",
"main": "server.js",
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js",
"test": "jest"
},
"dependencies": {
"express": "^4.18.2"
},
"devDependencies": {
"nodemon": "^3.0.0",
"jest": "^29.6.4"
},
"author": "Your Name",
"license": "MIT"
}
3. package-lock.json freezes the exact versions of installed packages. This
prevents unintended updates that might break the project.
4. Install package.json
To install package.json.
Open terminal and type: npm init -y
VI. Express
Express.js (often called Express) is a web framework for Node.js that makes building web
applications and APIs quick and easy. It provides a simple yet powerful toolkit for handling
HTTP requests, routing, middleware, and other web development features.

Why Use Express.js?

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:

npm init -y # Initialize a Node.js project


npm install express # Install Express.js

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:

1. The user enters https://example.com/products


2. The browser sends a request to the server (GET /products)
3. The server checks the URL and returns the corresponding content (HTML, JSON, etc.)
4. The browser displays the received content

The tutorial 9 is routing example


Server.js (Routing with http) Server.js (normal routing with express)
const http = require("http"); const express = require("express");
const app = express();
// Create server const port = 8000;
const server = http.createServer((req,
res) => {
console.log(`Request received for: $
{req.url}`);

if (req.url === "/") { app.get("/", (req, res) => {


res.writeHead(200, { "Content- res.send("Welcome to the Home Page!");
Type": "text/plain" }); });
res.end("Welcome to the Home
Page!"); app.get("/student", (req, res) => {
} res.send("Welcome to the Student
else if (req.url === "/student") { Page!");
res.writeHead(200, { "Content- });
Type": "text/plain" });
res.end("Welcome to the Student app.get("/admin", (req, res) => {
Page!"); res.send("Welcome to the Admin Page!");
} });
else if (req.url === "/admin") {
res.writeHead(200, { "Content- app.get("/data", (req, res) => {
Type": "text/plain" }); res.json({
res.end("Welcome to the Admin message: "This is a JSON response",
Page!"); students: [
} { id: 1, name: "Alice" },
else if (req.url === "/data") { { id: 2, name: "Bob" }
res.writeHead(200, { "Content- ]
Type": "application/json" }); });
const data = { });
message: "This is a JSON
response", // Start server
students: [ app.listen(port, () => {
{ id: 1, name: console.log(`Server is running at
"Alice" }, http://localhost:${port}`);
{ id: 2, name: "Bob" } });
]
};
res.end(JSON.stringify(data));
}
else {
res.writeHead(404, { "Content-
Type": "text/plain" });
res.end("404 Not Found");
}
});

// Start server on port 8000


server.listen(8000, () => {
console.log("Server is running at
http://localhost:8000");
});

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

GET Retrieves data from the server


POST Sends data to the server
PUT Updates an entire resource
PATCH Partially updates a resource
DELETE Removes a resource
Example all type of routing in express

All_type_routing.js
const express = require("express");
const app = express();
const port = 8000;

app.get('/users', (req, res) => {


res.send('Retrieve user list');
});

app.post('/users', (req, res) => {


res.send('Add a new user');
});

app.put('/users/:id', (req, res) => {


res.send(`Update user with ID ${req.params.id}`);
});

app.delete('/users/:id', (req, res) => {


res.send(`Delete user with ID ${req.params.id}`);
});

// Start server
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});

3. Routing with parameter


All_type_routing_parameter.js
const express = require("express");
const app = express();
const port = 8000;

app.use(express.json()); // Middleware to handle JSON body

// GET - Retrieve user list (Supports Query Parameters)


app.get('/users', (req, res) => {
const { page, limit } = req.query; // Extract query string parameters
res.send(`Retrieve user list - Page: ${page || 1}, Limit: ${limit || 10}`);
});
// POST - Add a new user (Uses Body Parameters)
app.post('/users', (req, res) => {
const { name, email } = req.body; // Extract data from the request body
res.send(`User Created - Name: ${name}, Email: ${email}`);
});

// PUT - Update user information (Uses URL Parameter + Body)


app.put('/users/:id', (req, res) => {
const userId = req.params.id; // Extract ID from URL
const { name, email } = req.body; // Extract update data from request body
res.send(`User ID ${userId} Updated - Name: ${name}, Email: ${email}`);
});

// DELETE - Delete a user by ID (Uses URL Parameter)


app.delete('/users/:id', (req, res) => {
const userId = req.params.id;
res.send(`User with ID ${userId} has been deleted`);
});

// Start server
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});

Test with postman


 Get

 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.

Server.js (Routing with http) Server.js (normal routing with express)


const express = require("express");
const app = express();
const port = 8000;

app.get('/users', (req, res) =>


res.send('Users list'));
app.post('/users', (req, res) =>
res.send('Add user'));
app.put('/users/:id', (req, res) =>
res.send('Update user'));
app.delete('/users/:id', (req, res) =>
res.send('Delete user'));

app.get('/products', (req, res) =>


res.send('Product list'));
app.post('/products', (req, res) =>
res.send('Add product'));
users.js
app.get('/orders', (req, res) =>
res.send('Order list'));

app.listen(port, () => const express = require("express");


console.log(`Server running on port $ const router = express.Router();
{port}`));
router.get("/", (req, res) =>
res.send("Retrieve user list"));
router.post("/", (req, res) =>
res.send("Add user"));
router.put("/:id", (req, res) =>
res.send(`Update user ${req.params.id}`));
router.delete("/:id", (req, res) =>
res.send(`Delete user ${req.params.id}`));

module.exports = router;

products.js
const express = require("express");
const router = express.Router();

router.use(express.json()); // Middleware
for parsing JSON

// 🟢 GET - Retrieve product list


router.get("/", (req, res) => {
res.send("Retrieve product list");
});

// 🔵 POST - Add a new product


router.post("/", (req, res) => {
const { name, price } = req.body;
res.send(`Product Created - Name: $
{name}, Price: ${price}`);
});

// 🟠 PUT - Update a product


router.put("/:id", (req, res) => {
const { id } = req.params;
const { name, price } = req.body;
res.send(`Product ID ${id} Updated -
Name: ${name}, Price: ${price}`);
});

// 🔴 DELETE - Delete a product


router.delete("/:id", (req, res) => {
const { id } = req.params;
res.send(`Product with ID ${id} has
been deleted`);
});

module.exports = router;

Server.js

const express = require("express");


const app = express();
const port = 8000;

// Import route modules


const userRoutes =
require("./routes/users");
const productRoutes =
require("./routes/products");
const orderRoutes =
require("./routes/orders");

app.use(express.json()); // Middleware to
parse JSON

// Use routes
app.use("/users", userRoutes);
app.use("/products", productRoutes);
app.use("/orders", orderRoutes);

// Start the server


app.listen(port, () => {
console.log(`🚀 Server is running at
http://localhost:${port}`);
});

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);

Exercise: write code for orders.js

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).

users.js no controller Breake down into 2 files


usersController.js
const express = // Get all users
require("express"); exports.getAllUsers = (req, res) => {
const router = express.Router(); res.send("Retrieve user list");
};
router.get("/", (req, res) =>
res.send("Retrieve user list")); // Create a new user
router.post("/", c(req, res) => exports.createUser = (req, res) => {
res.send("Add user")); const { name, email } = req.body;
router.put("/:id", (req, res) => res.send(`User Created - Name: $
res.send(`Update user $ {name}, Email: ${email}`);
{req.params.id}`)); };
router.delete("/:id", (req, res)
=> res.send(`Delete user $ // Update user
{req.params.id}`)); exports.updateUser = (req, res) => {
const { id } = req.params;
module.exports = router; const { name, email } = req.body;
res.send(`User ID ${id} Updated -
Name: ${name}, Email: ${email}`);
};

// Delete user
exports.deleteUser = (req, res) => {
const { id } = req.params;
res.send(`User with ID ${id} has
been deleted`);
};

Users.js call controller


const express = require("express");
const router = express.Router();
const userController =
require("../controllers/usersControlle
r");

router.get("/",
userController.getAllUsers);
router.post("/",
userController.createUser);
router.put("/:id",
userController.updateUser);
router.delete("/:id",
userController.deleteUser);

module.exports = router;

Finish all other controller files

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.

✅ Hot Reloading – No need to restart the server manually.


✅ Speeds Up Development – Automatically detects changes and restarts.
✅ Works with Any Node.js Application – No modifications required.

To install nodemon
npm install -g nodemon
to check it has installed
nodemon –v

To use nodemon in your project


Install package.json
npm init –y
then update your package.json file add the yellow line of code
{
"name": "express_hello",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"express": "^4.21.2"
}
}

To run your application: npm run start

VIII. Mongoose

IX. Restful Api

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy