Sometimes, we want to use socket.io in Express 4 and express-generator’s /bin/www.
In this article, we’ll look at how to use socket.io in Express 4 and express-generator’s /bin/www.
How to use socket.io in Express 4 and express-generator’s /bin/www?
To use socket.io in Express 4 and express-generator’s /bin/www, we can add the socket.io initialization code in its own file.
For instance, in socketApi.js, we write
const io = require("socket.io")();
const socketApi = {
io,
};
io.on("connection", (socket) => {
console.log("A user connected");
});
module.exports = socketApi;
to call io.on
with 'connection'
to listen for the connection
event.
We export the socketApi
with
module.exports = socketApi;
Then in /bin/www, we incorporate the socket.io code with
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);
//...
We call require
to require the socketApi.js
file.
Then we call socketApi.io.attach
with the Express server
to run the socket.io initialization code when we run our Express server.
Conclusion
To use socket.io in Express 4 and express-generator’s /bin/www, we can add the socket.io initialization code in its own file.