Categories
JavaScript Answers

How to use socket.io in Express 4 and express-generator’s /bin/www with JavaScript?

Spread the love

To use socket.io in Express 4 and express-generator’s /bin/www with JavaScript, we create a module with the socket.io code.

For instance, we write

const io = require("socket.io")();
const socketApi = {
  io,
};

io.on("connection", (socket) => {
  console.log("A user connected");
});

module.exports = socketApi;

in socketApi.js to listen for client connections by call on with 'connection' and the event handler.

We export the socketApi object with the io object.

Then we write

const app = require("../app");
const debug = require("debug")("socketexpress:server");
const http = require("http");
const socketApi = require("../socketApi");

const port = normalizePort(process.env.PORT || "3000");
app.set("port", port);

const server = http.createServer(app);
socketApi.io.attach(server);

to import the socketApi file with require("../socketApi").

Then we call socketApi.io.attach to attach the Express server to it.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *