JavaScript Answers

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

Spread the love

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

For instance, we write

const io = require("")();
const socketApi = {

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

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

Then we call 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 *