Reputation: 2043
Assume that I have two files.
server.js
test.js
server.js have all the initialization codes in place (Mongoose, Express..etc). It also has the below code:
const io = require('socket.io')(server);
In my test.js file, I have something related to mqtt. It is irrelevant, however, please understand that I don't have any variable access in there (req, app). Because that file isn't part of the route or anything.
It is included in server.js as:
require('test.js');
I am not getting into any details of MQTT or how it works. Consider that one or more functions inside test.js is running on a specific time. So, when ever that happens, how can I emit an event using socket.io from the test.js file?
My client side dashboard is ready to receive the event. I am just confused how to design the system, especially how to access the io
variable which exist in server.js
file.
Upvotes: 0
Views: 192
Reputation: 138557
As mentioned already just export a function from test.js that takes io
as a parameter:
module.exports = function test(io) {
io.on("connection", socket => {
socket.emit("greeting", "hello world!");
});
};
From your server.js you just have to pass in the argument:
require("./test.js")(io);
Upvotes: 1