Easy Tutorial
❮ Nodejs Express Framework Nodejs Process ❯

Node.js Functions

In JavaScript, a function can be passed as an argument to another function. We can define a function first and then pass it, or we can define the function directly where the parameter is 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 pass the say function as the first variable to the execute function. Here, what is passed is not the return value of say, but say itself!

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

Of course, since say has a parameter, execute can pass a parameter when calling someFunction.


Anonymous Functions

We can pass a function as a variable. However, we don't necessarily have to go through the "define first, then pass" process. We can define and pass the function directly within the parentheses of another function:

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

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

We define the function we intend to pass to execute directly where the first parameter is accepted.

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 Works in an HTTP Server

With this knowledge, let's look again at our simple yet concise 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 be clearer: we pass an anonymous function to the createServer function.

This code can 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);
❮ Nodejs Express Framework Nodejs Process ❯