Node.js functions


In JavaScript, a function can receive a parameter as another function. We can define a function first and then pass it, or we can define the function directly where the parameters are passed.

The use of functions in Node.js is similar to Javascript. For example, you can do this:

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

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

execute(say, "Hello");

In the above code, we use the say function as the first variable of the execute function. passed on. What is returned here is not the return value of say, but say itself!

In this way, say becomes the local variable someFunction in execute. execute can use the say function by calling someFunction() (with parentheses).

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


Anonymous function

We can pass a function as a variable. But we don't have to go around this "define first, then pass" circle. We can directly define and pass this function in the brackets of another function:

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

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

Where we accept the first parameter in execute Directly defines the function we are going to pass to execute.

In this way, we don’t even need to give the function a name, which is why it is called an anonymous function.


How function passing makes the HTTP server work

With this knowledge, let’s take a 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 should look a lot clearer: we passed an anonymous function to the createServer function.

The same purpose can be achieved with code like this:

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);