Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 278
hoge Avatar asked Mar 28 '26 22:03

hoge


1 Answers

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.

like image 159
Angular University Avatar answered Apr 01 '26 07:04

Angular University



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!