Node. js Lesson 4 (callback functions and events)

Source: Internet
Author: User

Callback handler 1. callback function 1. asynchronously read the file var fs = require ('fs'); fs.readFile('file.txt ', 'utf-8', function (err, data) {if (err) {console. log (err)} else {console. log (data) }}); console. log ('end. ') Result: end. contents of the file. 2. synchronous File Reading var fs = require ('fs'); var data‑fs.readfilesync('file.txt ', 'utf-8'); console. log (data) console. log ('end. ') Result: Contents of the file. end. 3. analysis: the work done during the call sends the asynchronous IO request to the operating system, then immediately returns and executes the following statement. And then enters the event loop listening event. When fs receives the event that completed the IO request. The event loop actively calls the callback function to complete subsequent work. Synchronization continues after the synchronization is completed. Ii. Event 1. use a common event // declare the event object 'var EventEmitter = require ('events '). eventEmitter; var event = new EventEmitter (); // register the event. on ('some _ event', function () {console. log ('this is a custom event');}); // trigger event setTimeout (function () {event. emit ('some _ event');}, 1000); 2. node. js event Loop Mechanism (1) Node. when Will js go into the event loop? The answer is that the Node. js program starts from the event loop and ends with the event loop. All the logic is the Event Callback Function. (2) how to use custom events? When the callback function of an event is executed, it may send an IO request or directly launch an (emit) event. After the execution is complete, it returns an event loop.

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.