Right now, I have app.js where I have my usual code and my socket.io code. But what I want to do is, separate every single code of socket.io into 1 different file and require that socket.io code from the different file into my main app.js. Is there any way to do it writing 2/3 lines of code into my app.js to require socket.io from a different file?
Note: I do not want to write any of my socket.io code into my app.js so I do not know if it would be possible to require('....') it into my app.js from a different file. Ideally want to separate everything within io.on('connection'){}
const express = require('express'); const http = require('http'); // socket.io is created upon http server. A way to create server const cors = require('cors'); const {Server} = require('socket.io'); const app = express(); app.use(cors()); const server = http.createServer(app); // this is to create http server with express for socket.io const io = new Server(server, { cors: { origin: "http://localhost:3000", methods: ["GET", "POST"] } }); io.on("connection", (socket) => { socket.on("newUser", (username) => { addNewUser(username, socket.id); console.log('connect print: '); printUsers(); }) socket.on("disconnect", () => { removeUser(socket.id); console.log('disconnect print: '); printUsers(); }); }) server.listen(3001, () => { console.log('server listening on port 3001'); })