3

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?

1
  • Where is module.js required? Commented Feb 25, 2013 at 16:49

2 Answers 2

4

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);
Sign up to request clarification or add additional context in comments.

Comments

3

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.