express 根目录获取问题?在线等 急
发布于 9 年前 作者 dmKiller 8270 次浏览 最后一次编辑是 8 年前 来自 问答

(function() {

var home = require('../app/controllers/home');


module.exports = function(app) {

    app.get('/', home.index);

};

}).call(this); require(’…/app/controllers/home’); 这个是通过本文件的相对路径去获取home Module。 这样情况下我如果移动了这个文件,那么这个require可能获取不到了。 如何直接是获取到项目根目录,然后从上往下去写路径 而不是这么从下往上去写?请问如何实现,我在express的API里看的可能不够细致,请指导指导

8 回复

process.cwd()

app.use(function(req, res, next) {
  req.server_path = path.join(__dirname, 'public');
  return next();
});

@i5ting 存到req里怎么在外部用?

在你的app.js里保存 __dirname 变量

__dirname
The name of the directory that the currently executing script resides in.

@hezedu 楼主的 home.index 是个 route,so home.index = function(req, res, next) { req.server_path }

不过貌似 process.cwd() 效果更好

@klesh process.chdir()可以改变process.cwd()的。 我现在的做法是把根目录存在conf 里。

嗯,可以达到目的就好,不过有chdir的情况会发生吗?

@hezedu 但是您将这个放在conf中,您要用的时候需要引入conf,这样又需要相对路劲去引入了。。。

回到顶部