node. js 0 Basic Detailed tutorial (4): node. js event Mechanism, node asynchronous IO operation

Source: Internet
Author: User
Tags readfile install node

The fourth chapter recommends 3 hours of study time 10 chapters

How to learn: read it in detail and implement the relevant code manually

Learning Goals : This tutorial will teach you to install node, build servers, Express, MySQL, MongoDB, write background business logic, write interfaces, and finally complete a complete project backstage, a total of 10 days is expected.

node. js Event mechanism

node. js is single-threaded, but with events and callbacks that support concurrency, you can achieve very high performance.

All of the APIs for node. JS are called asynchronously. In the first class, we wrote a synchronous and asynchronous example (below), which was originally said: The synchronous code executes before executing the asynchronous code.

SetTimeout (function() {    console.log (1000000000);},0);  for (var i=0; i<1000; i++) {    console.log (i);}

And for asynchronous multiple code, what is the order of execution? Try the following code:

Today's code we put in a new folder, in order to complete the following file read, we need to prepare a a.txt file in advance (Note: The file format is preferably uft-8)

The following code is written in Main.js:

var // node built-in module can be directly introduced into  FS: File system Operation module fs.readfile ("./a.txt", "utf-8",function(err,data) {  //  Read the file    ifthrow  err;    Console.log (data);}); SetTimeout (function() {    console.log ("Timer print! ");},0);

After you run main.js with node, you will notice that the timer is printed first (increase the timer's trigger time, and you will notice that the order of the printing will change.) )

The specific sequence of asynchronous code execution is controlled by the internal mechanism of node. js, which is difficult to predict accurately. Here we introduce the event model of node. JS:

node. JS uses the event-driven model, when the Web server receives the request, shuts it down and processes it, and then goes to service the next Web request.

When this request is completed, it is put back into the processing queue, and when it arrives at the beginning of the queue, the result is returned to the user.

This model is very efficient and extensible because webserver always accepts requests without waiting for any read and write operations. (This is also known as non-blocking IO or event-driven IO)

In the event-driven model, a main loop is generated to listen for events and trigger a callback function when an event is detected.

callback function

A callback function is one that passes a function as a parameter to another function, as a function that executes inside another function.

In the file read method in the example above, the third parameter is a callback function, which is automatically called when the file read is complete.

Fs.readfile ("./a.txt", "utf-8",function(err,data) {  // Read file    if  Throw  err;    Console.log (data);});

The callbacks above are encapsulated, so let's write the implementation of a callback function ourselves:

Create a JS file and write the following code:

 function   Fn01 (data,callback) { if   ",data);  else  { var  err = new  error (" Error " "AA", function   (err, Data) { if   (err) {Console.log ( "error" +    err);    }  else  {console.log (data); }})

The above code is the standard model of the callback function, when we call Fn01, we pass in two parameters, the first one is a string, the second is a callback function, when the parameter is passed in. Let's take a look at the main method of Fn01, which detects the existence of the first parameter, and then executes the callback method, which is the method that the parameter passed in.

Asynchronous IO Operations

We are talking about the way the file is read all at once, when the file is too large, a one-time read not only slow, and affect the user experience, then how to achieve step-by read it,

This has to be done using asynchronous Io, which flows out like a stream for a period of time.

Specific implementation:

We create a file read stream, first on the code

varFS = require ("FS");vardata = "";//declares an empty string to store the read datavarrs = Fs.createreadstream ("A.txt"); Rs.setencoding ("Utf-8");//Listen, when there's data flowing in,Rs.on ("Data",function(chunc) {data+ = Chunc;//The data that is being read is stitched onto data. Console.log ("...");//in the process of reading, we print three points. }); Rs.on ("End",function() {Console.log ("No data.")});

We will increase the content in the a.txt to make the read time longer,

Code, create main3.js write the above code, use Reatereadstream to create a read stream object, use on the object to listen to "data" to read the event, each read a piece of data, will trigger this event, when read, it will trigger an "end" event.

With the execution of Main3.js, we can see the results printed below, from multiple lines of printed "...", and we can see that reading is done more than once.

Will read to the data, slowly write to the B.txt

Modify the code in Mai3.js as follows, add the following line of code 4/10/16, 4 lines to establish a write stream (if the file is not present, will automatically create a file), 10 lines to write to the file, 16 lines to close the write stream.

1 varFS = require ("FS");2 3 varrs = Fs.createreadstream ("A.txt");4 varWS = Fs.createwritestream ("B.txt");//Write Stream5Rs.setencoding ("Utf-8");6 7 //Listen, when there's data flowing in,8Rs.on ("Data",function(chunc) {9Console.log ("...");//in the process of reading, we print three points. TenWs.write (Chunc, "utf-8");//write something to a file One }); A  -  -Rs.on ("End",function(){ theConsole.log ("No Data Anymore"); -Ws.end ();//Close Write Stream -});

This allows us to read and write the files asynchronously.

OK, so much for today, tomorrow will explain: Express routing.

node. js 0 Basic Detailed tutorial (4): node. js event Mechanism, node asynchronous IO operation

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.