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

15,211

Solution 1

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

Solution 2

Just remove the 200, Check below code

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

http.createServer(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);
Share:
15,211
Kunal Tyagi
Author by

Kunal Tyagi

Updated on June 27, 2022

Comments

  • Kunal Tyagi
    Kunal Tyagi almost 2 years

    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.