Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting "TypeError: "listener" argument must be a function" in Node.Js

Tags:

node.js

app.js

var url = require('url');
var http = require('http');
var fs = require('fs');

http.createServer(200, function(req, res){
  var q = url.parse(req.url, true);
  var filename = "." + q.pathname;
  fs.readFile(filename, function(err, data){
    if(err)
    {
        res.writeHead(404, {'Content-Type' : 'text/html'});
        return res.end("404 Not Found!!!");
    }
    res.writeHead(200, {'Content-Type' : 'text/html'});
    res.write(data);
    return res.end();
  });
}).listen(8080);

When I try to run it using the command "node app.js", I am getting the following error:

events.js:238
    throw new TypeError('"listener" argument must be a function');
    ^

TypeError: "listener" argument must be a function
    at _addListener (events.js:238:11)
    at Server.addListener (events.js:298:10)
    at new Server (_http_server.js:263:10)
    at Object.createServer (http.js:35:10)
    at Object.<anonymous> (E:\AngularJS\New folder\app2.js:7:6)
    at Module._compile (module.js:573:30)
    at Object.Module._extensions..js (module.js:584:10)
    at Module.load (module.js:507:32)
    at tryModuleLoad (module.js:470:12)
    at Function.Module._load (module.js:462:3)

I tried to find out the solution but wasn't able to resolve it. Thanks in advance.

like image 582
Kunal Tyagi Avatar asked Mar 09 '23 04:03

Kunal Tyagi


1 Answers

http.createServer expects only a function, with 2 callback items (response, request). Simply remove 200 from your createServer call or replace it with this:

http.createServer(function(req, res) { ... }

You can read more about this here: https://nodejs.org/api/http.html#http_http_createserver_requestlistener

like image 147
James Gould Avatar answered Apr 08 '23 13:04

James Gould