【问题标题】:Unable to import app.js in other modules in expressJs无法在expressJs的其他模块中导入app.js
【发布时间】:2017-02-09 18:31:49
【问题描述】:

我无法在 expressJs 的其他模块中导入 app.js。它正在导入,但我无法使用 app.js 文件中定义的函数

我的代码是这个- 我有这个 app.js

var app = express();
var expressWs = require('express-ws')(app);
.
.
.
wss= expressWs.getWss();

// console.log(wss);  // works fine
app.getWss=function(){
  return "hello";
  };
app.listen(3001);
module.exports = app;

在 /socketroutes/socketroutes.js 内的文件中

var app = require('../app');
console.log(app); // prints an empty object {}
console.log(app.getWss())  // returns undefined function and doesn't work

我想在其他模块中使用 app.js 中定义的一些变量或函数。因为 websocket 服务器的实例应该只创建一次。我无法在每个模块中创建 wss 实例。

【问题讨论】:

  • 你有什么错误吗?

标签: javascript node.js express websocket


【解决方案1】:

这主要是因为循环依赖。 尝试将 module.exports 行移到 app.js 文件的开头。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-06
    相关资源
    最近更新 更多