Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't run Socket.io server, TypeError: Server is not a constructor

I’m trying to run socket.io, with express Js. Below is my code of server.js

const express = require("express");
const app = express();
const http = require("http");
const cors = require("cors");
const Server = require("socket.io");

app.use(cors());
 const server = http.createServer(app);

const io = new Server(server, {
  cors: {
    origin: "http://localhost:3000",
    methods: ["GET", "POST"],
  },
});

io.on("connection", (socket) => {
  console.log(`User connected: ${socket.id}`);
  socket.on("Disconnect", () => {
    console.log(`User disconnected: ${socket.id}`);
  });
});

server.listen(3000, () => {
  console.log("SERVER WALKING");
});

And after running nodemon server.js via scripts.

I get this error

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const io = new Server(server, {
           ^

TypeError: Server is not a constructor
    at Object.<anonymous> (Path:10:12)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Module._load (node:internal/modules/cjs/loader:827:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47

Node.js v18.0.0
[nodemon] app crashed - waiting for file changes before starting...

Can anyone help me to point out what I’m doing wrong in this scenario.

I tried removing and re-adding node_modules, both with npm and yarn but still showing same error.

>Solution :

Use const { Server } = require("socket.io"); to import the Server class in socket.io library.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading