简体   繁体   English

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

[英]Unable to import app.js in other modules in expressJs

I am Unable to import app.js in other modules in expressJs. 我无法在expressJs中的其他模块中导入app.js. It's importing but i am unable to use functions defined in app.js file 它正在导入,但我无法使用app.js文件中定义的函数

Code i have is this- I have this 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;

in a file inside /socketroutes/socketroutes.js 在/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

I want to use some variables or functions defined in app.js in another modules. 我想在另一个模块中使用app.js中定义的一些变量或函数。 because instance of websocket server should be created only once. 因为websocket服务器的实例应该只创建一次。 i cannot create instance of wss in every module. 我不能在每个模块中创建wss的实例。

It's mostly because of a circular dependency. 这主要是因为循环依赖。 Try moving the module.exports line to the beginning of the app.js file. 尝试将module.exports行移动到app.js文件的开头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM