2

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'); }) 

1 Answer 1

5

There would be a few way to do this but something like below should work.

In your new file, use module.exports to export an object containing any functions or objects you want to export:

//socketio.js module.exports = { getIo: (server) => { const io = new Server(server, { //... }); io.on("connection", (socket) => { //... } //your other functions return io; } } 

Then in your app.js, require it and use the object's properties:

//app.js const socketio = require('./socketio.js'); //after creating your server etc const io = socketio.getIo(server); 
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you so much arf. If someone comes across or finds this helpful, please upvote the answer. I have insufficient reputation to cast it myself.
Glad it helped, FiFi. You should be able to accept the answer as correct if it is so. Thanks!
Done. Thanks again. Would you mind looking this as well? Having a really hard time with it. stackoverflow.com/questions/71842932/…
@arfi720 How can I add getBroadcast() or getSocket() to this file to access it to do somthing like this: socket.broadcast.to('game').emit('message', 'nice game');

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.