0

I'm really confused about this section

http://nodejs.org/api/http.html#http_http_createserver_requestlistener

The requestListener is a function which is automatically added to the 'request' event.

What does the term "added" specifically mean?

Also for here http://nodejs.org/api/http.html#http_event_request

What does the the code directly beneath mean function (request, response) { }? Does it mean that that function gets passed each time there is a request?

2 Answers 2

2

The requestListener is a lsitener that listens to the 'request' event. Each time a request event is emitted, the requestListener is executed. You pass a function.

That function you pass, should match:

function (request, response) { }

I believe there is an example at the main page of nodejs.org.

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

So each time a request-event is emitted, this function is 'called'.

function (req, res) {
      res.writeHead(200, {'Content-Type': 'text/plain'});
      res.end('Hello World\n');
    }

With req and res a parameters. (Request and response).

Sign up to request clarification or add additional context in comments.

3 Comments

I'm confused still... The requestListener is a function which is automatically added to the 'request' event. So this listener function is added to the request event? I thought the listener function executes each time there is a request.
Well, I think they mean with 'added', that is bound to the event, that it executes when the event is emitted.
Indeed, that would be better suited. They probs meant added as in: When the event is triggered, the function will be triggered too. So the function is added inside the event.
1

If it is any help the statement

var app = http.createServer( function reqlistener(request, response){...} ).listen(1337);

where the function reqlistener is the requestListener argument, is equivalent to the following

var app = http.createServer().listen(1337);
app.on('request', function reqlistener(request, response){...} );

So it is just a shortcut for providing a listener for event request during server start itself. The event request is emitted for each request once when received by the server.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.