在主节点文件中使用 modules.exports

Using modules.exports in main Node file

我在我的 server.js 文件(主入口点)中初始化了我的 socket.io 服务器。

编辑 2: 在此文件中也导入 otherfile.js

// server.js
const io = require('socket.io')(server);
const otherfile = require('otherfile.js');
io.use(//...configuration);
io.on("connection",otherfile);

module.exports = {io: io}

现在我想在另一个文件中使用同一个 io 对象

编辑 1: 为了澄清,我在导出块中调用导出变量,如下所示:

// otherfile.js

const io = require('./server.js')['io'];

module.exports = {
    function(socket){
        // do stuff...
        io.emit("event", payload);
          }
}

当我 运行 它时,我得到一个错误

Type Error: Cannot read '.on' property of undefined

类似的东西。

为什么我无法从主 js 文件访问代码?

我在阅读 this great article(好吧,它的一部分 :p)关于在 Node.js 中需要模块之后弄明白了。 "Circular Module Dependency".

问题是,我在导出 io 对象 之后 我需要 'otherfile.js' 所以 io 对象还没有已导出,因此在调用代码时在 'otherfile.js' 中未定义。

所以在需要 'otherfile.js' 之前导出 io 对象。

// server.js
module.exports = {
     io: io
     }
 const otherfile = require("otherfile.js");
 // listen for events...