Cris
Cris

Reputation: 12204

How do i access app variables from other modules in node.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);

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

Upvotes: 3

Views: 3447

Answers (2)

hhh
hhh

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

Pascal Belloncle
Pascal Belloncle

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

Related Questions