Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

283
Views
express.js - single routing handler for multiple routes

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!

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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'));
about 4 years ago · Santiago Trujillo Report

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;
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!