Node.js: create application + callback function (blocking/non-blocking)

1. Create an application

  If we use PHP to write the back-end code, we need Apache or Nginx HTTP server with mod_php5 module and php-cgi. From this point of view, the whole "receive HTTP request and serve Web page" requirement doesn't need PHP to handle at all.

  But for Node.js, the concept is completely different. When using Node.js, we are not only implementing an application, but also an entire HTTP server. In fact, our web application and corresponding web server are basically the same.

  Before we create our first "Hello, World!" application in Node.js, let's first understand what parts a Node.js application consists of:

  1. Introducing required modules: We can use the require directive to load Node.js modules.

  2. Create a server: The server can listen to client requests, similar to HTTP servers such as Apache and Nginx.

  3. Receiving requests and responding to requests The server is easy to create, the client can use a browser or terminal to send HTTP requests, and the server returns the response data after receiving the request

1. Introduce the required module

  We use the require command to load the http module and assign the instantiated HTTP to the variable http. The example is as follows:

2. Create a server

  Next we use the http.createServer() method to create the server and use the listen method to bind port 8888. Functions receive and respond to data through request, response parameters.

  For example, create a file called server.js in the root directory of your project and write the following code:

var http = require("http")

http.createServer(function(request,response){
    // Send HTTP headers 
     // HTTP status value: 200 : OK
     // Content type: text/plain 
    response.writeHead( 200 , { ' Content-Type ' : ' text/plain ' });

    // Send response data "Hello World" 
    response.end( ' Hello World\n ' );
}).listen(8888)

//The terminal prints the following information 
console.log( ' Server running at http://127.0.0.1:8888/ ' );

  With the above code we have completed a working HTTP server. Use the node command to execute the above code, open the browser and visit http://127.0.0.1:8888/, you will see a webpage that says "Hello World".

  Analyze the HTTP server of Node.js: The first line requires the http module that comes with Node.js and assigns it to the http variable. Next we call the function provided by the http module: createServer . This function returns an object with a method called listen, which takes a numeric parameter specifying the port number on which this HTTP server listens.

2. Callback function

  The direct embodiment of asynchronous programming in Node.js is the callback. Asynchronous programming relies on callbacks to achieve, but it cannot be said that the program is asynchronous after using callbacks. The callback function will be called after the task is completed. Node uses a large number of callback functions. All Node APIs support callback functions. For example, we can execute other commands while reading the file, and after the file is read, we return the file content as the parameter of the callback function. This way there is no blocking or waiting for file I/O operations while the code is executing. This greatly improves the performance of Node.js, which can handle a large number of concurrent requests.

1. Blocking code example

var fs = require("fs");
var data = fs.readFileSync('input.txt');

console.log(data.toString());
console.log("程序执行结束!");
//结果:先打印input里面内容,再打印程序结束

2、非阻塞代码实例

var fs = require("fs");
fs.readFile('input.txt', function (err, data) {
    if (err) return console.error(err);
    console.log(data.toString());
});

console.log("程序执行结束!");
//结果:先打印程序结束,再打印input里面内容

  以上两个实例我们了解了阻塞与非阻塞调用的不同。第一个实例在文件读取完后才执行完程序。 第二个实例我们不需要等待文件读取完,这样就可以在读取文件时同时执行接下来的代码,大大提高了程序的性能。

  因此,阻塞是按顺序执行的,而非阻塞是不需要按顺序的,所以如果需要处理回调函数的参数,我们就需要写在回调函数内。

3、阻塞和非阻塞,同步异步的理解

  阻塞和非阻塞,同步和异步是node.js里经常遇到的词汇,我举个简单的例子来说明:

  我要看足球比赛,但是妈妈叫我烧水,电视机在客厅,烧水要在厨房。家里有2个水壶,一个是普通的水壶,另一个是水开了会叫的那种水壶。我可以:

  (1)用普通的水壶烧,人在边上看着,水开了再去看球。(同步,阻塞)这个是常规做法,但是我看球不爽了。

  (2)用普通水壶烧,人去看球,隔几分钟去厨房看看。(同步,非阻塞)这个又大问题,万一在我离开的几分钟水开了,我就麻烦了。

  (3)用会叫的水壶,人在边上看着。(异步,阻塞)这个没有问题,但是我太傻了。

  (4)用会叫的水壶,人去看球,听见水壶叫了再去看。(异步,非阻塞)这个应该是最好的。

  等着看球的我:阻塞,看着电视的我:非阻塞

  普通水壶:同步,会叫的水壶:异步

  所以,异步往往配合非阻塞,才能发挥出威力。

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325395378&siteId=291194637