hoge
hoge

Reputation: 65

Using socket.io in multi files

I am using Node.js Express with socket.io.

//app.js
var server = http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});
var io = require('socket.io').listen(server,{'log level': 1});

and if I want to do "io.sockets.emit" only for people watching index page which is provided by index.js how can I call "io.sockets.emit" in index.js other than using "require" for app.js(main file)?

I've googled about it though I couldn't find any sample source code which use socket.io in multiple files.

Upvotes: 3

Views: 3571

Answers (1)

Angular University
Angular University

Reputation: 43127

If your backend is separated in several module files like index.js, it's possible to pass variables to modules upon initialization.

Try importing index.js after initializing socket.io, and pass io to the index.js module being imported:

require('./index.js')(io); 

See also this answer.

Upvotes: 2

Related Questions