TypeError: require(...).listen is not a function

23,328

Solution 1

require('socket.io') returns the socket.io Server class. It's a class, not an instance and thus not something you call .listen() on. Depending upon what exactly you're trying to accomplish, there are a number of different ways you can use that Server class as you can see here in the doc. For example, you can do this:

const Server = require('socket.io');
const io = new Server(somePort);

or this:

const io = require('socket.io')(somePort);

or to share an existing http server:

const io = require('socket.io')(plainHttpServer);

Solution 2

The below snippet worked for me:

const io = require('socket.io')(server);
...
server.listen(3000)
Share:
23,328
user1467328
Author by

user1467328

Updated on July 05, 2022

Comments

  • user1467328
    user1467328 almost 2 years

    I wrote this, but errors come up and i dont know how to fix

    var http = require('http');
    var clientHtml = require('fs').readFileSync('client.html');
    
    var plainHttpServer = http.createServer(function (request, response) {
    response.writeHead(200, { 'Content-Type': 'text/html' });
    response.end(clientHtml);
    }).listen(8080);
    
    var files = require('fs');
    
    var io = require('socket.io').listen(plainHttpServer);
    io.set('origins', ['localhost:8080', '127.0.0.1:8080']);
    

    and this error comes, i don't know how to fix, tell me

    var io = require('socket.io').listen(plainHttpServer);
                              ^
    
    TypeError: require(...).listen is not a function
    
  • Squivo
    Squivo about 3 years
    Just to add to this - versions prior to the latest did support the listen() function