0

I'm currently building an app and I have a routes file that looks like this.

const router = require('express').Router();

router.get('/', (req, res) => res.render('statics/home'));
router.get('/jobs', (req, res) => res.render('statics/jobs'));
router.get('/about-page', (req, res) => res.render('statics/about-page'));
router.get('/valves', (req, res) => res.render('statics/valves'));

router.all('*', (req, res) => res.notFound());

module.exports = router;

I am trying to figure out a way to refactor my routes and have a single route that accepts any string and then checks to see if a file exists matching it

Any help appreciated!

2 Answers 2

1

To easily handle static file, you can use express static, express will automatic route all file inside static folder

app = require('express')();
app.use('statics',express.static('statics'));
Sign up to request clarification or add additional context in comments.

Comments

0

Something like this could work:

const router = require('express').Router();
const fs = require('fs');

router.get(':template', (req, res) => {
  const tpl = req.param('template');
  if (tpl) {
    if (fs.existsSync('/path/to/templates/' + tpl + '.ext')) { // adjust the path and template extension
      res.render('statics/' + tpl);
    } else {
      res.notFound();
    }
  } else {
    res.render('statics/home');
  }
});

router.all('*', (req, res) => res.notFound());

module.exports = router;

Or probably better approach would be to read the templates directory once and create routes based on its contents:

const router = require('express').Router();
const fs = require('fs');

const templates = fs.readdirSync('/path/to/templates');
templates.forEach(tpl => {
  tpl = tpl.substring(tpl.lastIndexOf('/') + 1);
  if (tpl === 'home') {
    router.get('/', (req, res) => res.render('statics/home'))
  } else {
    router.get('/' + tpl, (req, res) => res.render('statics/' + tpl))
  }
});

router.all('*', (req, res) => res.notFound());

module.exports = router;

1 Comment

This is exactly what I was looking for. Thanks very much! I really like the second solution you posted. I will try to implement this today

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.