Skip to content

Instantly share code, notes, and snippets.

@kosaikham
Created December 30, 2019 08:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kosaikham/13d86d88120309009511b46a89183c7e to your computer and use it in GitHub Desktop.
Save kosaikham/13d86d88120309009511b46a89183c7e to your computer and use it in GitHub Desktop.

How to separate websocket logic and app.js in Nodejs

// in app.js

let app = express();
//....
//....

const http = require('http').createServer(app);
require('./socket/index').listen(http);

//...
//...

http.listen(port, () => console.log(`Server is listening on port: ${port}`));

// in socket/index.js

const socketIO = require('socket.io');
module.exports.listen = app => {
    let io = socketIO.listen(app);
	exports.sockets = io.sockets;

    io.on('connection', function(socket) {
        //...
        //...
        socket.on("eventOne",() => {
            // ...
        })

        socket.on("eventTwo", () => {
            // ...
        })
    }

    return io
}

// wanna access from other files

const {sockets} = require('../socket/index').sockets;

sockets.sockets["testSocketID"].emit("testEvent", {
	message: "message body"
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment