javascript - 无法在expressJs中导入其他模块中的app.js

标签 javascript node.js express websocket

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

我的代码是这样的- 我有这个 应用程序.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 实例。

最佳答案

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

关于javascript - 无法在expressJs中导入其他模块中的app.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39804059/

相关文章:

javascript - 在别处单击时关闭 Material UI 组件

php - 错误 : TypeError: document. getElementById ("count2") 为空,因为条件表。怎么修?

css - style.css 在我的应用 Node js/express 中找不到

node.js - connect/expressjs 中的 "signed"cookie 是什么?

javascript - ui-router 没有替换 index.html 中的 ui-view

javascript - Google + 登录按钮会打开一个 Google 窗口,但窗口中什么也没有出现,然后它会关闭

node.js - Node/npm : How to reinstall/recompile copied app packages

javascript - 如何在 mongodb 中维护排序的属性顺序?

node.js - 为什么我们为 Node 使用服务器端模板引擎?

javascript - 无法读取未定义 Express API 的属性 'count'