# NodeJS & ExpressJS

### **Introduction**

**Node.js** is a powerful, event-driven, non-blocking JavaScript runtime that allows developers to build **scalable and high-performance backend applications**. It is built on **Google Chrome's V8 JavaScript engine**, making it **fast and efficient** for server-side development.

**Express.js** is a lightweight and flexible **web framework for Node.js**, designed to simplify the process of building web applications and APIs. It provides essential features like **routing, middleware, and HTTP handling**, making backend development smoother.

### **Why Use Node.js?**

* **Asynchronous & Non-blocking** – Handles multiple requests efficiently.
* **High Performance** – Uses **V8 Engine**, which compiles JavaScript to machine code.
* **Single Programming Language** – JavaScript can be used for both **frontend** & **backend**.
* **Huge Ecosystem** – Over **1.5 million packages** available via **npm**.
* **Microservices & Real-time Apps** – Ideal for **APIs, chat apps, and live streaming**.
* **Scalability** – Perfect for handling thousands of concurrent users.

### **Why Use Express.js?**

* **Minimal & Fast** – No unnecessary bloat; just the essentials.
* **Easy Routing System** – Handles URLs efficiently.
* **Middleware Support** – Customize requests and responses.
* **Template Engines** – Supports **EJS, Pug, and Handlebars** for dynamic HTML.
* **API Development** – Ideal for creating RESTful & GraphQL APIs.

## **Getting Started with Node.js & Express.js**

### **1️⃣ Install Node.js**

Download and install Node.js from <https://nodejs.org>.\
Check the installation:

```bash
node -v   # Check Node.js version
npm -v    # Check npm version

```

### **2️⃣ Initialize a New Project**

Create a new project and set up `package.json`:

```bash
mkdir myapp && cd myapp
npm init -y

```

3️⃣ Install Express.js

```bash
npm install express

```

## **Creating a Simple Express Server**

**Create a `server.js` file and add the following:**

```javascript
const express = require("express");
const app = express();
const PORT = 3000;

app.get("/", (req, res) => {
  res.send("Hello, World! 🌍");
});

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

```

Run the server:

```bash
node server.js

```

Now, open **<http://localhost:3000/>** in your browser.&#x20;

## **Express.js Routing**

**Defining Different Routes**

```javascript
app.get("/", (req, res) => {
  res.send("Home Page");
});

app.get("/about", (req, res) => {
  res.send("About Page");
});

app.post("/submit", (req, res) => {
  res.send("Data Submitted Successfully");
});

```

Handling URL Parameters

```javascript
app.get("/user/:name", (req, res) => {
  res.send(`Hello, ${req.params.name}!`);
});

```

**Visit:** `http://localhost:3000/user/John`\
**Output:** `"Hello, John!"`<br>

## **Using Middleware in Express.js**

Middleware functions allow you to **modify requests/responses** before they reach the final handler.

**Example of Middleware**

```javascript
app.use((req, res, next) => {
  console.log(`Incoming Request: ${req.method} ${req.url}`);
  next(); // Call the next middleware or route handler
});

```

**Built-in Middleware**

```javascript
app.use(express.json());       // Parse JSON requests
app.use(express.urlencoded({ extended: true }));  // Parse form data

```

**Third-party Middleware (CORS, Morgan)**

```bash
npm install cors morgan

```

```javascript
const cors = require("cors");
const morgan = require("morgan");

app.use(cors());   // Enables cross-origin requests
app.use(morgan("dev")); // Logs requests in console

```

## **Serving Static Files (HTML, CSS, Images, JS)**

Express can serve **static files** from a directory like `public/`.

```javascript
app.use(express.static("public"));

```

Place **HTML, CSS, JS, images** inside the `public/` folder, and access them directly in the browser.

## **Handling Forms & JSON Data**

&#x20;**Install Body Parser (Optional, built-in in Express 4.16+)**

```bash
npm install body-parser

```

Parse Form Data & JSON Requests

```javascript
const bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

```

Handling Form Submissions

```javascript
app.post("/login", (req, res) => {
  const { username, password } = req.body;
  res.send(`Logged in as ${username}`);
});

```

## **Connecting Express.js with a Database**

### **MongoDB (Using Mongoose)**

**Install Mongoose**

```bash
npm install mongoose

```

**Connect to MongoDB**

```javascript
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/mydb", {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

const UserSchema = new mongoose.Schema({ name: String, age: Number });
const User = mongoose.model("User", UserSchema);

// Create a User
app.post("/users", async (req, res) => {
  const user = new User(req.body);
  await user.save();
  res.send("User saved!");
});

```

## **Building a REST API with Express.js**

**Create a Simple API**

```javascript
const products = [
  { id: 1, name: "Laptop", price: 1000 },
  { id: 2, name: "Phone", price: 500 },
];

// Get all products
app.get("/api/products", (req, res) => {
  res.json(products);
});

// Get a single product by ID
app.get("/api/products/:id", (req, res) => {
  const product = products.find((p) => p.id == req.params.id);
  product ? res.json(product) : res.status(404).send("Not found");
});

// Create a new product
app.post("/api/products", (req, res) => {
  const newProduct = req.body;
  products.push(newProduct);
  res.status(201).json(newProduct);
});

```

## **Real-time Apps with Socket.io**

**Install Socket.io**

```bash
npm install socket.io

```

**Simple WebSocket Chat App**

```javascript
const http = require("http").createServer(app);
const io = require("socket.io")(http);

io.on("connection", (socket) => {
  console.log("User connected");
  socket.on("message", (msg) => io.emit("message", msg));
});

http.listen(3000, () => console.log("Chat server running on port 3000"));

```

## **Conclusion**

Node.js & Express.js are **powerful tools** for building **scalable, fast, and efficient** backend applications. Whether you're creating **REST APIs, real-time apps, or full-stack projects**, they provide everything you need.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.anandisheladiya.com/skills-and-experience/backend/nodejs-and-expressjs.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
