Skip to content Skip to sidebar Skip to footer

Get Access To Express Mountpath From Inside A Module

In an attempt to build a truly modular express app (one that can run stand alone or as a part of another app) I need to find out the cleanest way to find the mount path from inside

Solution 1:

As answered by alsotang, this is actually a problem of execution sequence, but it can be solved in what I think is a clean way. There is an event that is fired after the module is mounted, so you can do:

var truePath = = "/";

app.on('mount', function (parent) {
  truePath = app.mountpath;
});

Where in real life truePath could be app.locals.truePath, so it can be accessed from inside the views.

Solution 2:

eh..It's a problem of execution sequence.

In your subapp.js, the app.mountpath statement is before module.exports = app.

But only you export the app, then the app be mounted, then it would be set the mountpath property.

so, you should retrieve mountpath after the app be mounted by outer express.

My suggestion are two:

  1. set the mountpath in your subapp.js. And outer express read this property.
  2. perhaps you think 1 is not truly modular. so you can alternatively define a config file. and both main.js and subapp.js read mountpath from the config.

Solution 3:

Try req.baseUrl:

app.js

var express = require('express');
var app = express();
var foo = require('./foo');

app.use('/foo', foo);

app.listen(3000);

foo.js

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

router.get('/', function(req, res) {
  console.log(req.baseUrl); // '/foo'
  res.send('foo');
});

module.exports = router;

Post a Comment for "Get Access To Express Mountpath From Inside A Module"