从模块内部访问Express安装路径 [英] Get access to Express mountpath from inside a module
问题描述
在尝试构建真正的模块化Express应用程序(可以独立运行或作为其他应用程序的一部分运行)时,我需要找到最干净的方法来从子应用程序内部查找安装路径.举一个简短的例子,假设有两个文件:main.js和subapp.js
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 the subapp. For a short example, lets say that there are two files: main.js and subapp.js
main.js
main.js
var express = require('express');
var app = express();
var localApp = express();
var subapp = require('./subapp');
app.use('/foo', subapp);
app.use('/bar', localApp);
console.log(localApp.mountpath); // yes, this prints '/bar' as expected
...
subapp.js
subapp.js
var express = require('express');
var app = express();
var truePath = app.mountpath; // I wish this would point to '/foo', but instead points to '/'
...
module.exports = app;
从模块内部查找安装路径的最佳方法(如最干净的方法)是什么?我正在尝试解决此问题:以非有线方式使用express 从模板内部访问mountpath变量
What is the best way (as in cleanest) to find the mountpath from inside the module? I'm doing this trying to solve this problem: Access to mountpath variable from inside a template using express in a non hardwired way.
如示例中所示,已经使用app.mountpath尝试了成功
As shown in the example, tried already with app.mountpath without success
推荐答案
正如Alsotang回答的那样,这实际上是执行顺序的问题,但可以用我认为是干净的方法来解决.有一个在安装模块后触发的事件,因此您可以执行以下操作:
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;
});
在现实生活中, truePath 可能是 app.locals.truePath
,因此可以从视图内部对其进行访问.
Where in real life truePath could be app.locals.truePath
, so it can be accessed from inside the views.
这篇关于从模块内部访问Express安装路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!