Latest web development tutorials

Node.js function

In JavaScript, a function as a parameter to another function receives. We can define a function, and then pass to be defined directly in the transfer function of the place.

Node.js use a function similar to Javascript, for example, you can do this:

function say(word) {
  console.log(word);
}

function execute(someFunction, value) {
  someFunction(value);
}

execute(say, "Hello");

The above code, we say the function as the first argument execute functions were passed. This return is not the return value of say, but say itself!

Thus, say becomes execute local variables someFunction, execute by calling someFunction () (in the form of parentheses) to say the use of the function.

Of course, because say there is a variable, execute can pass such a variable when calling someFunction.


Anonymous function

We can put a function passed as an argument. But we do not have to about this "first defined, and then pass," the circle, we can define another function in parentheses and pass this function:

function execute(someFunction, value) {
  someFunction(value);
}

execute(function(word){ console.log(word) }, "Hello");

We accept the first argument in the execute directly defines where we are ready to pass to execute the function.

In this way, we do not even have a name for this function, which is why it is called an anonymous function.


Transfer function is how to get HTTP server work

With this knowledge, we look at our simple but not simple HTTP server:

var http = require("http");

http.createServer(function(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}).listen(8888);

Now it looks much should be clear: we pass an anonymous function to createServer function.

Such a code can also achieve the same purpose:

var http = require("http");

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

http.createServer(onRequest).listen(8888);