2013-03-10 68 views
0

这是我app.js外观的Node.js入门使用在其他模块需要时未定义的属性

var app = require('http').createServer(handler), 
    io = require('socket.io').listen(app), 
    static = require('node-static'); // for serving files 
var game = require('./game.js').createGame(); 

// This will make all the files in the current folder 
// accessible from the web 
var fileServer = new static.Server('./'); 

// This is the port for our web server. 
// you will need to go to http://localhost:8080 to see it 
app.listen(8080); 

// Listen for incoming connections from clients 
io.sockets.on('connection', function (socket) { 
    handle Events ... 
}); 

exports.io = io; 
exports.game = game; 

,当我尝试访问创建socket.io听者或游戏实例,我得到错误说其未定义。 这我怎么想访问它的绝招,JS

var game = require('./app.js').game; 
var socketio = require('./app.js').io; 
var PlayerMove = require('./playerMove.js'); 

这可能是因为trick.js是app.js(我把调试点,确认有)前实际执行。我如何避免这种情况?是否有更好的方法暴露node.js中的对象实例,我应该使用一些模式?

回答

1

声明一个变量不会导出它。如果您需要为模块导出某些内容,则应该使用exports.myVariable = myValue。

需要你的app.js文件第一次运行它。所以你输出的所有东西都会在require()调用后可用

+0

我以为我用'exports.game = game;'输出变量'game'的变量值,那么为什么我当我尝试在其他文件中使用require访问它时,将其设置为undefined – nesta13 2013-03-20 02:42:32

+0

只需在您的头部运行它 – Floby 2013-03-20 09:33:56

相关问题