I'm trying to set up this node server that serves three things:
-- An angular application that is in the /dist directory
-- An apiRest that is in the /api/index directory and handles the middleware
-- A chat with socket.io that listens on the same port 3001 and whose code is between the two double lines.
I have a question that I don't know how to solve:
- How can I separate the chat code to another module. I have tried to put it in a different file but I don't know how to pass it the server that is created in: const "server = http.createServer(app);"
All the best.
const express = require('express');
const path = require('path');
const http = require('http');
const socketIO = require('socket.io');
const cfg = require('./config/config')
const middleware = require('./middleware');
const app = express();
middleware.useMiddleware(app);
// Configuración de rutas
require('./api/index')(app);
const options = {
extensions: ['htm', 'html'],
maxAge: '1d',
setHeaders: res => res.set('x-timestamp', Date.now())
}
app.use(express.static(path.join(__dirname, '/dist'), options));
app.use(express.static(path.join(__dirname, '/dist/assets'), options));
const server = http.createServer(app);
console.log("==============================================");
const io = socketIO(server);
var onlineUsers = [];
io.on('connection', (socket)=> {
let query = socket.handshake.query;
let token = query.token;
let usu = {
'id': socket.id,
'codigo': query.usuCodigo,
'nome': query.usuNome
}
onlineUsers.push(usu);
io.emit('onlineUsers', { type:'onlineUsers', 'usuarios': onlineUsers });
socket.on('disconnect', ()=> {
onlineUsers.splice(onlineUsers.indexOf(socket.id), 1);
let usu = JSON.stringify(onlineUsers);
io.emit('onlineUsers', { type:'onlineUsers', 'usuarios': usu });
});
socket.on('onlineUsers', () => {
let usu = onlineUsers;
io.emit('onlineUsers', { type:'onlineUsers', 'usuarios': usu });
});
socket.on('add-message', (message) => {
let mx = JSON.parse(message);
mx.data = new(Date);
io.emit('message', { type:'new-message', 'mensaxe': mx });
});
});
console.log("==============================================");
const porto = cfg.PORTO;
server.listen(porto, ()=> {
console.log(`Servidor correndo no oo ${porto}`);
})