I'm using socket.io to send and receive messages between the clients and a NodeJS HTTP server. So far, it works fine as all the code is in the app.js
main file, like this:
let express = require('express')
let app = express();
let http = require('http');
let server = http.Server(app);
let socketIO = require('socket.io');
let io = socketIO(server);
io.on('connection', (socket) => {
console.log('New user connected');
socket.on('new-message', (message) => {
console.log(message);
io.emit('new-message', message);
});
});
But now I have this case:
- When a user requests the
/compile
and/save
routes from the client app, the server needs to do a few operations (that can take up to 2s each) and I'd like to keep him informed sending messages through socket.io to show the result of each operation. This is an example route handler:
routes/compile.js
var express = require('express');
var router = express.Router();
router.get('/compile', (req, res, next) => {
// DO THE OPERATIONS
// For each operation, send a socket.io message to the client with the result
});
The socket
for each client is obtained in the main file, when they connect to the server (io.on('connection', (socket) => {
), so how could I use it inside the routes?
Hope I explained it well, the nodeJS/socket.io combination is blowing my mind... Thanks!