is it possible to emit events inside some other node.js server files? Like I have the app.js running and also an other file running as well.
Inside the other server file I have
var io = require('socket.io');
And further in the files something like this (I want to send this data - price to the client).
io.emit('price', { price: price});
The error I get is io.emit is not a function. Any idea what I'm doing wrong?
You need to have one io object that is hooked to your web server (to receive incoming socket.io connections) and then you need to share (via exporting or by calling a function and pass the io object) the one io object with any other file that wants to use it.
You don't show very much of your code, but imagine you initialize socket.io in your main express file:
app.js
var express = require('express');
var app = express();
var server = app.listen(8080);
var io = require('socket.io')(server);
// load msg module and give it the io variable
var msg = require('./msg.js')(io);
msg.js
// define module constructor that accepts the io variable
var io;
module.exports = function(importIO) {
io = importIO;
}
// elsewhere in the module
io.emit(...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With