node. JS: Create App + callback function (blocking/non-blocking)

Source: Internet
Author: User

First, create an application

If we use PHP to write back-end code, we need an Apache or Nginx http server, with MOD_PHP5 modules and php-cgi. From this perspective, the entire "Receive HTTP request and provide WEB page" requirement does not 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 implementing an entire HTTP server. In fact, our web application and the corresponding Web server are basically the same.

Before we create the first "Hello, world!" app for node. JS, let's start by understanding which parts of the node. JS application are composed:

    1. introducing the required module: We can use the require directive to load the node. JS module.

    2. Create server: The server can listen to the client's request, similar to Apache, Nginx and other HTTP server.

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

1. Introduction of Required Module

We use the require directive to load the HTTP module and assign the instantiated HTTP value to the variable HTTP, as shown in the following example:

2. Create a server

Next we use the Http.createserver () method to create the server and bind port 8888 using the Listen method. The function receives and responds to data through the request, response parameter.

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

varHTTP = require ("http") Http.createserver (function (request,response) {//Send HTTP Header//HTTP Status value: 200:ok//content Type: Text/plainResponse.writehead ( $, {'Content-type':'Text/plain'}); //Send response data "Hello World"Response.End ('Hello world\n');}). Listen (8888)//The terminal prints the following informationConsole.log ('Server running at http://127.0.0.1:8888/');

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

Parse the HTTP server for node. JS: The first line requests (require) node. js's own HTTP module and assigns it to the HTTP variable. Next we invoke the function provided by the HTTP module: Createserver. This function returns an object that has a method called Listen, which has a numeric parameter that specifies the port number that the HTTP server listens on.

second, callback function

The immediate manifestation of node. JS asynchronous programming is callbacks. Asynchronous programming relies on callbacks to implement, but it cannot be said that the program is asynchronous after using the callback. The callback function is called after the task is completed, and node uses a large number of callback functions, and all node APIs support the callback function. For example, we can read the file while executing other commands, and after the file is read, we return the contents of the file as parameters to the callback function. This will not block or wait for file I/O operations when executing code. This greatly improves the performance of node. JS and can handle a large number of concurrent requests.

1. Blocking Code Instances

var fs = require ("fs"); var data = Fs.readfilesync ('input.txt'); Console.log (data.tostring ()); Console.log (" program execution is over! ") " ); // Result: The contents of input are printed first, and then the printing program ends.

2. Non-blocking code instances

 var  fs = require (  " fs   "   "  Input.txt   " , function (err, data) { Span style= "COLOR: #0000ff" >if  (Err) return      Console.error (err); Console.log (Data.tostring ());}); Console.log (  "  program execution ends!   "  //  result: Print the program end first, then print the contents of input   

Above two examples we understand the difference between blocking and non-blocking calls. The first instance finishes executing the program after the file has been read. In the second instance, we don't have to wait for the file to be read, so we can execute the next code while reading the file, which greatly improves the performance of the program.

As a result, blocking is performed sequentially, not blocking is not required in order, so if you need to handle the parameters of the callback function, we need to write it inside the callback function.

3, blocking and non-blocking, synchronous asynchronous understanding

Blocking and non-blocking, synchronous and asynchronous are frequently encountered words in node. js, and I'll give you a simple example to illustrate:

I want to watch the football game, but my mother told me to boil water, TV in the living room, boil water to be in the kitchen. There are 2 kettles in the house, one is an ordinary kettle, the other is the kind of kettle that the water will call. I can:

(1) burn with a common kettle, the person looks at the side, the water opens again to see the ball. (synchronous, blocking) This is a normal practice, but I don't see the ball.

(2) Use the ordinary kettle to burn, people go to see the ball, every few minutes to the kitchen to see. (synchronous, non-blocking) this big problem, in case I left the water for a few minutes, I was in trouble.

(3) with the kettle that will be called, people look at the edge. (async, blocking) that's fine, but I'm stupid.

(4) with the kettle that will be called, people go to see the ball, heard the kettle called again to see. (asynchronous, non-blocking) this should be the best.

Waiting to see the ball of me: blocking, watching TV me: non-blocking

Ordinary kettle: synchronous, will call the kettle: Async

Therefore, asynchronous often with non-blocking, can play the power.

node. JS: Create App + callback function (blocking/non-blocking)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.