Home > Software design >  Express.js file-system based router
Express.js file-system based router

Time:12-18

I just would like to ask, is it possible to do file-system based routing with express.js routes? Something like Next.js has.

CodePudding user response:

Well, I do not recommend this as it can turn out to be a security issue. However if you really want to, it is quite easy to do. You can just listen to app.get("*"). An example shown below:

let path = require("path")
let express = require("express")
let app = express()
let fs = require("fs")

app.listen(80)

app.get("*", (req,res) => {
    let filePath = path.join(__dirname, "routes", req.path)
    if(!fs.existsSync(filePath)) return res.sendStatus(404)
    res.sendFile(filePath)
})

This recurses and loads any file that may be there in the "routes" folder (or any subdirectories). I did this with html so i did sendFile(), however I believe it should work with .render() too.

I highly recommend against this as it can potentially allow people to climb up your directory structure with some messing around with the path they try to fetch.

  • Related