[go: up one dir, main page]

0% found this document useful (0 votes)
20 views11 pages

Expressjs

The document provides an introduction to Express.js, a flexible web application framework for Node.js that simplifies routing and middleware. It covers installation, creating a basic app, managing environment variables, and using a .env file for development. Additionally, it discusses serving static files and validating environment variables using the Zod library.

Uploaded by

Rakesh kumar
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)
20 views11 pages

Expressjs

The document provides an introduction to Express.js, a flexible web application framework for Node.js that simplifies routing and middleware. It covers installation, creating a basic app, managing environment variables, and using a .env file for development. Additionally, it discusses serving static files and validating environment variables using the Zod library.

Uploaded by

Rakesh kumar
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/ 11

Introduction to Express.

js

 Express.js is a minimal and flexible web application framework for Node.js based on http
module.
 It simplifies routing, middleware, and handling HTTP requests in Node.js applications.
 It is an extremely popular with wide community support.
 Alternatives: Fastify, Nest.js, Koa, Hono, Elysia.js
 Use npm install express command to install Express.js
o We are going to use Express.js v5 in this project which is already stable.
o For some reasons, directly installing express installs v4, which is why, you can use
npm install express@5 to install latest version.

PS E:\Nodejs\express> npm init


This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible
defaults.

See `npm help init` for definitive documentation on these fields


and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and


save it as a dependency in the package.json file.

Press ^C at any time to quit.


package name: (express)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
type: (commonjs)
About to write to E:\Nodejs\express\package.json:

{
"name": "express",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"type": "commonjs"
}

Is this OK? (yes)

PS E:\Nodejs\express> npm install express@5

added 66 packages, and audited 67 packages in 5s

14 packages are looking for funding


run `npm fund` for details

found 0 vulnerabilities
PS E:\Nodejs\express>

App.js
--
import express from "express";

const app = express();

// app 🔲 This variable holds the created Express app,


// which you can use to:
// Define routes (app.get(), app.post(), etc.)
// Configure middleware (app.use())
// Start the server (app.listen())
app.get("/", (req,res) =>{
res.send("Hello world");
});

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


res.send("<h1>About Page</h1>");
});

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


return res.send(`<div class="container">
<h1>URL Shortener</h1>
<form id="shorten-form">
<div>
<label for="url">Enter URL:</label>
<input type="text" name="url" id="url" required>
</div>
<div>
<label for="shortCode">Enter Shortcode:</label>
<input type="text" name="shortCode" id="shortCode" required>
</div>
<button type="submit">Shorten</button>
</form>

<h2>Shortened URLs</h2>
<ul id="shortened-urls"></ul>
</div>`);
});

const PORT = 3000;


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

Environment Variables

 Environment variables are used to store configuration values like port number, API keys,
database URLs, or secrets outside the codebase.
 Most platforms automatically add PORT environment variable which we can use.
 You can access environment variable using process.env. Process is a global object available
in Node.js.
 To access environment variable, you first have to set in your Operating System.
o For macOS, and Linux, you can use export VARIABLE_NAME="value" in your
terminal
o On Powershell, you can use $env:VARIABLE_NAME="value"
o On Command Prompt, you can use set VARIABLE_NAME=value
o If you want to set permanently on Linux, and macOS, you have to include that
command in your shell config (~/.bashrc, ~/.zshrc, etc.)
o If you want to set permanently on Windows, you can search “Environment Variables”
in windows search.

const PORT = process.env.PORT;


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

PS E:\Nodejs\express> $env:PORT=3000; node --watch ./app.js

.env file for development

 Setting environment variable using command is tedious in development, especially if you have
multiple projects.
 So, we typically use .env file to manage our environment variables.
 This isn’t a file which you will share with others as it includes sensitive information, so make
sure to include it in .gitignore. To let developers know which variables are needed, you can
include .env.example file with empty values.
 .env file typically has environment variables in this syntax: VARIABLE=value separated by
new line.
 After Node.js v20.6.0, we can directly include .env file using --env-file syntax.
 For older versions, you have to install a separate package named dotenv and import it in your
project.
o import 'dotenv/config'
o require('dotenv').config()
 Since, Node.js has this feature, we will use built-in feature for that.

Package.json
{
"name": "express",
"version": "1.0.0",
"description": "",
"license": "ISC",
"author": "",
"type": "module",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "node --env-file=.env --watch app.js"
},
"dependencies": {
"express": "^5.1.0"
}
}

.env
PORT = 3000;

App.js
const PORT = process.env.PORT;
app.listen(PORT, ()=>{
console.log(`Server is running at port: ${PORT}`);
});

Fix Port Number Issues in Node.js | Check, Release, and Set Ports
Using .env
---
PS E:\Nodejs\express> echo $env:PORT
3000
PS E:\Nodejs\express> Remove-Item env:\PORT
PS E:\Nodejs\express> echo $env:PORT
PS E:\Nodejs\express> npm run dev

> express@1.0.0 dev


> node --env-file=.env --watch app.js

Server is running at port: 3001;


Completed running 'app.js'

Validating Environment Variables

 You might have many environment variables in your project, and it's important to validate each
one to ensure they are all present and correct.
 You can either handle this manually or, preferably, use a validation library like Zod.
 Zod is a TypeScript-first schema declaration and validation library that allows you to define
and validate the structure of your data easily.
 We will be using Zod for various validations in the future, so we’ll also use it here to validate
environment variables.
Manual way:
--
Env.js
export const PORT = isNaN(process.env.PORT) ? 3001 :
parseInt(process.env.PORT);

app.js
import express from "express";
import {PORT} from "./env.js";

const app = express();

// app 🔲 This variable holds the created Express app,


// which you can use to:
// Define routes (app.get(), app.post(), etc.)
// Configure middleware (app.use())
// Start the server (app.listen())

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


res.send("Hello world");
});

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


res.send("<h1>About Page</h1>");
});

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


return res.send(`<div class="container">
<h1>URL Shortener</h1>
<form id="shorten-form">
<div>
<label for="url">Enter URL:</label>
<input type="text" name="url" id="url" required>
</div>
<div>
<label for="shortCode">Enter Shortcode:</label>
<input type="text" name="shortCode" id="shortCode" required>
</div>
<button type="submit">Shorten</button>
</form>

<h2>Shortened URLs</h2>
<ul id="shortened-urls"></ul>
</div>`);
});

// console.log(process);

// const PORT = 3000;


// const PORT = process.env.PORT || 3000;
app.listen(PORT, ()=>{
console.log(`Server is running at port: ${PORT}`);
});

With Zod:
---
PS E:\Nodejs\express_validating_env_zod> npm install zod

added 1 package, and audited 68 packages in 6s

15 packages are looking for funding


run `npm fund` for details

found 0 vulnerabilities

env.js
import {z, ZodError} from "zod";
const ageSchema = z.number().min(18).max(100).int();
const userAge = 17;

try{
const parseUserAge = ageSchema.parse(userAge);
console.log(parseUserAge); //success case
}catch(error){
//instanceof is a js operator used to check if an object is an instance of
a specific class or constructor.
if(error instanceof ZodError){
console.log(error.issues[0].message); //Display error message only
}else{
console.log("Unexpected error: ", error);
}
}

PS E:\Nodejs\express_validating_env_zod> node --watch ./env.js


Number must be greater than or equal to 18
EX: PORT
.env
PORT = "3000";

Env.js
// export const PORT = isNaN(process.env.PORT) ? 3001 :
parseInt(process.env.PORT);

import {z, ZodError} from "zod";


// const ageSchema = z.number().min(18).max(100).int();
// const userAge = 17;

// try{
// const parseUserAge = ageSchema.parse(userAge);
// console.log(parseUserAge); //success case
// }catch(error){
// //instanceof is a js operator used to check if an object is an instance
of a specific class or constructor.
// if(error instanceof ZodError){
// console.log(error.issues[0].message); //Display error message only
// }else{
// console.log("Unexpected error: ", error);
// }
// }

// const ageSchema = z.number().min(18).max(100).int();


// const userAge = 19;

// const parseUserAge = ageSchema.parse(userAge);


// const {data, error, success} = ageSchema.safeParse(userAge);
// // console.log(data);
// console.log(success);

//PORT validate using Zod


const portSchema = z.coerce.number().min(1).max(65535).default(3000);
export const PORT = portSchema.parse(process.env.PORT);

app.js
app.listen(PORT, ()=>{
console.log(`Server is running at port: ${PORT}`);
});
How to Send Files in ExpressJs
--
App.js
import express from "express";
import {PORT} from "./env.js";
import path from "path";

const app = express();

// console.log(__dirname);
// console.log(__filename);
app.get("/", (req,res) =>{
// console.log(import.meta.dirname);
// console.log(import.meta.url);
// const __filename = new URL(import.meta.url);
const __filename = new URL(import.meta.url).pathname;
console.log(__filename);
// res.send("Hi");

// res.send(` <div class="text-section">


// <h1>Never Loose hope</h1>
// <p>You are beautiful the way you are.
// Keep doing the good work.
// </p>
// <a href="#">God Bless You</a>
// </div>
// <div class="img"></div>`);

const homePagePath = path.join(import.meta.dirname, "public",


"index.html");
res.sendFile(homePagePath);

});

app.listen(PORT, ()=>{
console.log(`Server is running at port: ${PORT}`);
});
Static Files in Express.js

 Static files as name mentions are files which don’t change, these can be assets like images, css,
html, font, etc.
 Express has middleware named express.static("public") which we can use to serve static
files.
o We will learn about middleware in detail later.
 Files in the static directory are accessible via their URL. For instance, if you have an image
logo.png in the public folder, you can access it in the browser with
http://localhost:3000/logo.png.
 It will handle all files inside the directory provided.

EX:
--
App.js
--
import express from "express";
import {PORT} from "./env.js";
import path from "path";

const app = express();


// app.use(express.static("public"));
//absolute path
const staticPath = path.join(import.meta.dirname, "public");
app.use(express.static(staticPath));

// console.log(__dirname);
// console.log(__filename);
app.get("/", (req,res) =>{
// console.log(import.meta.dirname);
// console.log(import.meta.url);
// const __filename = new URL(import.meta.url);
const __filename = new URL(import.meta.url).pathname;
console.log(__filename);
// res.send("Hi");

// res.send(` <div class="text-section">


// <h1>Never Loose hope</h1>
// <p>You are beautiful the way you are.
// Keep doing the good work.
// </p>
// <a href="#">God Bless You</a>
// </div>
// <div class="img"></div>`);

const homePagePath = path.join(import.meta.dirname, "public",


"index.html");
res.sendFile(homePagePath);

});

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

You might also like