Search code examples
node.jsexpressrouterexpress-router

Nodejs pass variable from router file to another router file


i need to pass a variable called path from router file lessonsRouter.js to another router file lessons.js

My folder structure

routes
|
+--lessons.js
|
+--lessonsRouter.js

lessonsRouter.js

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

router.get('/*/([A-Z][a-z]+)/README.md', (req, res) => {
  const path = req.url; // the variable that i need to pass to lessons.js router

// ignore next three lines
  const pathSeparate = req.url.split('/');
  const LessonTopic = pathSeparate[1].toLowerCase()
  const LessonName = pathSeparate[2].match(/[A-Z][a-z]+/g).join('-').toLowerCase();

  res.locals.path = path;
  res.redirect(`/lessons/${LessonTopic}/${LessonName}`);
});

router.use('/:topic/:name', lessons);

module.exports = router;

lessons.js

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

router.get('/', (req, res) => {
  // i want to use variable path from lessonsRouter.js here

});
module.exports = router;

Solution

  • I would argue that you have your dependency/import direction wrong. lessons should import from lessonsRouter. But if you really want it this way, then you can export a function to which you can pass the path once you have it.

    lessonsRouter.js

    const lessons = require('./lessons');
    
    router.get('/*/([A-Z][a-z]+)/README.md', (req, res) => {
      const path = req.url; // the variable that i need to pass to lessons.js router
      lessons(path);
      ...
    });
    

    lessons.js

    module.exports = (path) => {
      router.get('/', (req, res) => {
        console.log(path);
      });
    };