I am quite new to node.js and don't understand how to solve the following:
I have an express app and want to use socket.io in a sub file to get smaller code blocks - I want to excclude the socket.io part to a file called data.js - from what I have read here this is a proper way to use io on sub-files:
const express = require('express'); const app = express(); const http = require('http'); const server = http.createServer(app); const io = require('socket.io')(server); require('.data')(io); // .... start server etc. below. in the data.js file i have:
const consola = require('consola'); module.exports = function (io) { io.on('connection', (socket) => { consola.success(`User connected - ${io.engine.clientsCount} online`); socket.on('disconnect', (socket) => { consola.success(`user disconnected :(`); }); }); }; so far that works. I have acces to io in the data.js. Now I want to emit a message outside the function(io). Reason is that I have an interval in the data.js that checks for new data. When it detects new data, the data should be forwarded via socket.io to the connected clients. But I don't want to put the interval inside the 'connection' as this would trigger a new interval evertime a user joins. So I want to emit from another function inside data.js...
can someone please point me to the right direction please. I already found some solutions here, but it seems they all only work if you have the sockets logic in the file with the express logic.
Many thanks in advance.