Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Node .js function


May 10, 2021 Node.js


Table of contents


Node .js function

In JavaScript, one function can receive an argument as another. We can define a function first, then pass it, or we can define a function directly where the arguments are passed.

Node .js functions in the node system 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 passed the say function as the first variable of the execute function. W hat is returned here is not the return value of say, but the say itself!

As a result, say becomes the local variable someFunction in execute, and execute can use the say function by calling someFunction() (in 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. B ut we don't have to go around this "define first, pass before pass" circle, and we can define and pass this function directly in parentheses of another function:

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

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

Where execute accepts the first argument, we define directly the function that we are going to pass to execute.

In this way, we don't even have to name this function, which is why it's called an anonymous function.


How function delivery makes the HTTP server work

With this knowledge, let's take a look at our simple but not simple HTTP servers:

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.

You can do the same 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);