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