Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

542
Views
How to separate all of socket.io to a different file

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');
})
about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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);
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!