Joshua H Joshua H - 3 years ago 226
Javascript Question

createServer method in Node.js

I've been looking over this basic example in order to set up a simple server in Node, however I am really struggling to understand where the 'request' and 'response' parameters are coming from. Where do they point to and how?

// Load the http module to create an http server.
var http = require('http');

function onRequest(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("Hello World\n");

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(onRequest);

// Listen on port 8000, IP defaults to

Usually when passing paramaters into a function I pass something I can see, like a variable equal to 5, or 'Hello', but in this case I'm not...

Sorry if this is not explained very well!

Answer Source

When you call createServer, you are passing the function onRequest to it:

var server = http.createServer(onRequest);

This pattern is known as a callback: you pass a function to someone else, with the expectation that they will call your function if something interesting has happened.

In essence, you are saying to Node,

Hey, please create an HTTP server for me. Whenever you receive a request, call my function onRequest with the request and response objects passed as parameters.

Another way to do this is to listen to the request event, which takes the same parameters in its callback.

The parameters are documented as being http.IncomingMessage and http.ServerResponse. You can call them whatever you want, but request and response are the idiomatic parameter names. (Some people use req and res because they are shorter to type.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download