如何从Node.js中的其他模块访问应用程序变量? [英] How do i access app variables from other modules in node.js?

查看:80
本文介绍了如何从Node.js中的其他模块访问应用程序变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用express 2和node 0.8访问app.js中声明的变量;我有以下代码:

I need to access variables declared in app.js using express 2 and node 0.8; i have the following code:

app.js
------
[.....]
var server = app.listen(3000);
var io = require('socket.io');
io.listen(server);
exports.io=io;

module.js
----------
var app=require("./app");
console.log(app.io);

但是app.io是不确定的...我在做什么错了?

but app.io is undefined ... what am i doing wrong?

推荐答案

如果在app.js中设置exports.io的旁边添加console.log,则console.log(app.io).

If you add a console.log right next to when you set exports.io in app.js, this is likely to happen after console.log(app.io) runs in module.js.

相反,为了更好地控制顺序,可以在module.js中导出一个init函数,然后从app.js中调用它.

Instead, to better control the order, you could export an init function in module.js, and call it from app.js.

module.js

module.js

var io = null;
exports.init = function(_io) {
  io = _io;
}

app.js

var server = app.listen(3000);
var module = require('./module')
var io = require('socket.io');
io.listen(server);
module.init(io);

这篇关于如何从Node.js中的其他模块访问应用程序变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆