Synchronous and asynchronous and node JS callback functions

Source: Internet
Author: User

1. Create a input.txt text file and write something inside.

2. Create a Main.js file

Varfs = require("FS");  var data = fs.  Readfilesync('input.txt'); (This place must be prefixed with the name of the suffix)console.  Log(data.  ToString()); console.  Log("program execution ends!") ); 

3. The results of the code above for synchronization are as follows:
$ node main.  JS Rookie Tutorial official website address:www.  Runoob.  COM program execution ends!        

Async Code

1. Create a input.txt text file and write a little something. Note that text files must be suffixed

2. Create Main.js

VarFs= Require("FS");Fs.ReadFile(' Input.txt ', function (Err, data) { if (err) return console.  Error(err); console.  Log(data.  ToString()); }); console.  Log("program execution ends!") ); 
3. The result of the code execution is

Program execution ends!  Novice Tutorial Official website address:www.  Runoob.  Com

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.

Synchronous and asynchronous and node JS callback functions

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.