I created a queue system via Rabbitmq and send notifications to users via socket. There are 3 files basically.
-index.js //some functions to save data and send to Rabbitmq
-socket.js //socket io modules
-consumer.js //some functions to consume data from Rabbitmq
When npm run index.js and consumer.js are started.
index.js
const Express = require('express');
const app = Express();
//init server
server = app.listen(3000);
//init socket io
require('./socket').initialize(server);
socket.js
const sio = require('socket.io');
let io;
module.exports = {
//Initialize the socket server
initialize: (server) => {
io = sio(server, {
cors: {
origin: '*',
}
});
io.on('connection', (socket) => {
console.log('New client connected with id = ', socket.id);
socket.on('disconnect', () => {
console.log("User disconnected");
});
});
},
//return the io instance
getInstance: () => {
return io;
}
}
consumer.js
const socket = require('./socket');
const io = socket.getInstance();
console.log("io", io);
//io is undefined
Io returns undefined in consumer.js. Where is mistake?
CodePudding user response:
You can't call socket.getInstance() until someone has called socket.initialize() first.
You don't show where consumer.js is loaded so we can't follow the full sequence of module loading, but it appears that consumer.js is getting loaded before you initialize socket and thus it is trying to call socket.getInstance() before there's a socket instance to get.
When using methods that return state that built from previous methods, it is obviously important that things are called in the right order.
