Skip to Content
πŸ“š TutorialπŸ”— Express Js3) Static

Static File

Folder Structure

Let’s assume you have a folder like this

. β”œβ”€β”€ server.ts β”œβ”€β”€ package.json β”œβ”€β”€ tsconfig.json β”œβ”€β”€ πŸ“‚uploads β”‚ β”œβ”€β”€ πŸ“‚cars β”‚ β”‚ β”œβ”€β”€coolCars.jpeg β”‚ β”‚ β”œβ”€β”€ πŸ“‚moreCarFolder β”‚ β”‚ β”‚ └── cuteCar.jpeg β”‚ β”‚ └── adorableBMW.gif β”‚ β”œβ”€β”€ yolo.jpeg β”‚ β”œβ”€β”€ hello.html β”‚ └── πŸ“‚mouse β”‚ └── music.mp3 └── πŸ“‚public β”œβ”€β”€ index.js β”œβ”€β”€ index.html └── index.css

express.static() Usage

The express.static() can help to feed static file / folder without using res.send().

server.ts
import express from "express"; import { Request, Response } from "express"; const app = express(); app.get("/api", function (req: Request, res: Response) { res.end("Hello mom!"); }); // highlight-start // Add this line app.use(express.static("public")); app.use('/uploads', express.static("uploads")) // highlight-end const PORT = 8080; app.listen(PORT, () => { console.log(`Listening at http://localhost:${PORT}/`); });

To get the specific file, you may follow the regarind pattens.

app.use(express.static("public")); app.use('/uploads', express.static("uploads")) index.html http://localhost:8080/ yolo.jpeg http://localhost:8080/uploads/yolo.jpeg music.mp3 http://localhost:8080/uploads/mouse/music.mp3 adorableBMW.gif http://localhost:8080/uploads/cars/adorableBMW.gif cuteCar.jpeg http://localhost:8080/uploads/cars/moreCarFolder/cuteCar.jpeg

With __dirname

// Normal ways app.use(express.static("public")); // Defaulf is "/" path app.use('/uploads', express.static("uploads")) // Safe ways import path from "path" let uploadDir = path.join(__dirname, 'uploads') app.use('/uploads', express.static(uploadDir))

With middleware guard

import path from "path" import { Request, Response, NextFunction } from 'express'; app.use( "/upload", isValidUserGuard, express.static(path.join(__dirname, "..", '/upload')) ); export function isValidUserGuard( req: Request, res: Response, next: NextFunction ) { try { // Check the cookie or header that match your requirement if(req.cookies){ return next(); } throw new Error("Invalid access") } catch (error) { return res.status(501).json({ status: false, msg: "Permission Denied." }); } }
Last updated on