Home > Software engineering >  How can I nicely handle an ENOENT?
How can I nicely handle an ENOENT?

Time:02-07

I've recently started making an Express project. I made it so if someone goes to localhost:3000/games/tictactoe, they receive /games/tictactoe/index.html. (Edit: I want the routes to be dynamic; if a user goes to /games/foo, it should send them the index.html of that directory.) My directory structure is:

multiplayergames
├── games
│   └── tictactoe
│       └── index.html
└── src
    └── server.js

server.js (so far)

const express = require("express")
const app = express()
app.get("/games/:game", (req, res) => {
    res.sendFile(`${req.params.game}/index.html`, {root: "games/"})
})
  
app.listen(3000, () => {
    console.log(`App is up! (${new Date().toLocaleTimeString()})`)
})

The only problem is, if someone goes to, say, /games/foo, it says Error: ENOENT: no such file or directory, stat 'multiplayergames/games/foo/index.html'. Is there any way to send the user a "nicer" response (an HTML page) when they go to a nonexistent game?

[also, if there's something wrong with how I dynamically serve the files, let me know; I threw it together pretty quickly]

CodePudding user response:

you can use node fs to check if file exist, and return the game, or a custom html file. https://nodejs.org/api/fs.html#fsexistssyncpath

const fs = require('fs')
app.get("/games/:game", (req, res) => {
     if (fs.existsSync('/path/to/game/index.html')) {
       res.sendFile(`${req.params.game}/index.html`, {root: "games/"})
     } else {
       res.sendFile('custom 404 html file');
     }
})
  •  Tags:  
  • Related