Reputation: 12204
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);
but app.io is undefined ... what am i doing wrong?
Upvotes: 3
Views: 3447
Reputation: 2769
When you do the require
of module.js
make sure to pass the variable app
to the constructor. Example.
app.js
var app = express();
var mod = require('module')(app);
module.js
// Module constructor
var app;
var m = module.exports = function (_app) {
app = _app;
}
m.myFunction = function () {
// app is usable here
console.log(app);
}
Upvotes: 3
Reputation: 11389
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
.
Instead, to better control the order, you could export an init function in module.js
, and call it from app.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);
Upvotes: 4