I am trying to follow the instructions given by Patrick Roberts on this page:
How can i export socket.io into other modules in nodejs?
in my consumer.js when I call socket.emit('message') I get an error back: "Cannot read property 'emit' of null"
Why is emit not available to me?
Here is my code: io.js file (in a middleware directory)
var socketIO = require('socket.io');
var io = null;
exports.io = function() {
return io;
};
exports.initialize = function(server) {
io = socketIO(server);
io.on('connection', (socket) => {
console.log('user connected')
socket.emit('newMessage');
socket.on('hello', (msg) => {
console.log('message: ' + msg);
});
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
};
In app.js I am requiring the io file with:
var io = require('./middleware/io').initialize(server);
In my consumer.js I have the following:
var socket = require('../middleware/io').io();
and then from within a function I am calling:
socket.emit('message')
The emits coming from within the io.js file are working- its the ones I am trying to use in consumer.js that are not.