使用 module.exports 将 expressJS 中的服务器对象公开到另一个文件

Exposing server object in expressJS to another file using module.exports

在我正在构建的 expressJS 应用程序中,我需要将服务器对象公开给另一个文件,所以我想我可以这样做,从 app.js 文件到我的其中一个路由

var server = http.createServer(app).listen(4021, function () {

    var port = server.address().port;

    console.log('http://localhost:%d', port);
});

module.exports = server;

app.js 文件

我已经记录了这个文件中的变量,它包含一个关于 server.In 我的 routes.js 文件的一堆数据的对象,我认为会使用 require

将其引入
var server = require('../../server');

但是,如果我在服务器变量上使用 route.js 中的 console.log,它是一个空对象。任何想法我做错了什么

像您定义的那样的循环依赖项可能难以实现和调试。这不会具体回答你的问题,但如果端口号是你在路由中唯一需要的东西,那么我建议你采用更简单的方法。也许是将端口号添加到请求对象从而将其暴露给路由的中间件:

app.use(function(req, res, next) {
  req.port = 4021;
  next();
});

这是另一个与您的问题类似的 SO 问题:Expose vs Creating object in Router file of Nodejs。看一看,但我无法将其修改为您的示例。