Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 686
user1467328 Avatar asked Nov 20 '20 04:11

user1467328


People also ask

Why is require(...) is not a function?

The "require (...) is not a function" error occurs for multiple reasons: Forgetting to place a semicolon between the require call and an IIFE Calling the result of require () when the imported file doesn't have a default export of a function Having cyclic dependencies (imports and exports between the same modules)

Is it possible to listen on a 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 io = require ('socket.io') (server); ... server.listen (3000)

Why can't I listen to the HTTP module?

Since app is your http module var app = require ('http');, you were trying to listen to the node http module (and well you can't). You need to create a server with this http module and then listen to it.


1 Answers

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);
like image 125
jfriend00 Avatar answered Oct 12 '22 14:10

jfriend00