In-depth understanding of Node. js event loops and callback Functions

Source: Internet
Author: User
Tags emit
In-depth understanding of Node. js event loops and callback functions this article describes in detail the Node. js event loops and Node. js callback functions. If you don't talk about them much, let's take a look at them below.

I. Node. js event Loop

Node. js is a single-process, single-thread application, but supports concurrency through events and callbacks, so the performance is very high. Each API of Node. js is asynchronous and runs as an independent thread. It uses asynchronous function calls and processes concurrency. Basically, all the event mechanisms of Node. js are implemented using the observer mode in the design mode. Node. A single js thread enters a while (true) event loop until no event observer exits. Each asynchronous event generates an event observer. If an event occurs, the callback function is called.

1. Event drivers

Node. js uses the event-driven model. When the web server receives a request, it closes the request and processes it, And then serves the next web request. When the request is completed, it is put back into the processing queue. When it reaches the beginning of the queue, this result is returned to the user. This model is highly efficient and highly scalable because the web server keeps receiving requests without waiting for any read/write operations. (This is also called non-blocking IO or event-driven IO ). In the event-driven model, a main loop is generated to listen to events. When an event is detected, a callback function is triggered.

The entire event-driven process is implemented in this way and is very concise. Similar to the Observer mode, an event is equivalent to a topic, and all the handler functions registered to this event are equivalent to the Observer ). Node. js has multiple built-in events. We can bind and listen to events by introducing the events module and instantiating the EventEmitter class, as shown in the following example:

// Introduce the events module var events = require ('events'); // create the eventEmitter object var eventEmitter = new events. eventEmitter (); the following programs are bound to the event handler: // The event handler and event handler eventEmitter. on ('eventname', eventHandler); we can trigger the event through a program: // trigger the event eventEmitter. emit ('eventname ');

2. Instance

Create the main. js file with the following code:

// Introduce the events module var events = require ('events'); // create the eventEmitter object var eventEmitter = new events. eventEmitter (); // create the event handler var connectHandler = function connected () {console. log ('Connection successful. '); // Trigger the data_received event eventEmitter. emit ('data _ received');} // bind the connection event handler eventEmitter. on ('connection', connectHandler); // use an anonymous function to bind the data_received event eventEmitter. on ('data _ received', function () {console. log ('data received successfully. ') ;}); // Triggers the connection event eventEmitter. emit ('connection'); console. log ("the program has been executed. ");

Ii. Node. js callback function

The direct embodiment of Node. js asynchronous programming is callback. Asynchronous programming relies on callback, but it cannot be said that the program will be asynchronized after callback is used. The callback function is called after the task is completed. Node uses a large number of callback functions, and all APIs of Node support callback functions. For example, we can read the file while executing other commands. After reading the file, we will return the file content as a callback function parameter. In this way, the Code is not blocked or waiting for file I/O operations. This greatly improves Node. js performance and can process a large number of concurrent requests.

1. Blocking code instances

Create a file test.txt with the following content:

Hello World!fs.readFileSync()fs.readFile()

Create the test. js file with the following code:

Console. log ('------- program starts executing --------'); // introduces the fs module var fs = require ("fs"); // synchronously reads the file var data = fs.readFileSync('test.txt ', 'utf-8'); console. log (data. toString (); console. log ('------- program execution ends --------');

The code execution result is as follows:

2. Non-blocking code instance

Create the test. js file with the following code:

Console. log ('------- program starts executing --------'); // introduces the fs module var fs = require ("fs"); // The fs.readfile('test.txt ', 'utf-8 ', function (err, data) {if (err) return console. error (err); console. log (data. toString () ;}); console. log ('------- program execution ends --------');

In the above program, fs. readFile () is an asynchronous function used to read files. If an error occurs during file reading, the error err Object will output an error message. If no error occurs, readFile skips the output of the err Object, and the file content is output through the callback function.

The code execution result is as follows:
Next, delete the input.txt file. The execution result is as follows:
We understand the differences between blocking and non-blocking calls in the above two instances. The first instance executes the program only after the file is read. In the second instance, we do not need to wait for the file to be read, so that we can execute the following code while reading the file, greatly improving the program performance. Therefore, blocking is executed in sequence, but not in sequence. Therefore, if you need to process callback function parameters, you must write them in the callback function.

Iii. fs. readFileSync and fs. readFile

1. s. readFileSync

Syntax: fs. readFileSync (filename, [encoding])

Receiving parameters:

Filename: file path

Options: option object, including encoding, encoding format. This parameter is optional.

Because Node. js only supports the following encoding: utf8, ucs2, ascii, binary, base64, hex, and does not support Chinese GBK or GB2312 encoding, therefore, to read and write the Chinese content of files in GBK or GB2312 format, you must use an additional module: iconv-lite.

2. fs. readFile

Syntax: fs. readFile (filename, [encoding], [callback (err, data)])

Receiving parameters:

Filename: file path

Options: option object, including encoding, encoding format. This parameter is optional.

Callback: callback. Two parameters are passed: err and file content data.

Related Article

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.