In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
How to implement the event cycle in nodejs? aiming at this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible way.
When Node.js starts, the event loop is initialized, and each event loop contains a loop of six nodes, which is completely different from the browser event loop.
Each box in the figure is called a "phase" of the event loop, and the six stages are a round of event cycles.
Phase Overview
Timers (timer): this phase executes callback functions with setTimeout () and setInterval () schedules.
I callbacks O callback: almost all callback functions are executed at this stage, except for close callbacks (close callback) and those with timers and setImmediate () scheduling
Idle (idling), prepare: this phase is used internally only
Poll (polling): retrieve the new Icano event; Node will block at this node at the appropriate time
Check: the callback of the setImmediate () setting is called at this stage
Close callbacks (callback of shutdown event):
For example, socket.on ('close',...); callbacks of this type are called at this stage; between each run of the event loop, Node.js checks to see if it waits for asynchronous I _ UBO or timer, and automatically shuts down if it doesn't
If event loop enters the poll phase and the code does not set timer, the following occurs:
If the poll queue is not empty, the event loop will synchronously execute the callback in the queue, knowing that the queue is empty or that the executed callback reaches the upper limit of the system
If poll queue is empty, the following occurs:
If the code has been set by setImmediate (), callback,event loop will end the poll phase and enter the check phase, and execute the queue of the check phase (the queue of the check phase is set by setImmediate)
If the code does not set setImmediate (callback), event loop will block waiting for callbacks to join poll queue at this stage, and execute it as soon as it is reached
If event loop enters the poll phase and the code sets timer:
If the poll queue is empty (that is, the poll phase is idle), the event loop will block waiting for callbacks to join the poll queue at that stage, and execute it as soon as it is reached
SetImmediate is agreed on setTimeout (cb,0)
The path.resolve () method parses the sequence of a path or path fragment into an absolute path.
_ _ dirname always points to the absolute path of the current folder
_ _ filename always points to the absolute path of the current file
Note:
Io: the browser thread calls some asynchronous callbacks
Execute Code 1
Var fs = require ('fs'); var path = require (' path'); function someAsyncOperation (callback) {/ / cost 2ms fs.readFileSync ('. / read.txt', callback);} var timeoutScheduled = Date.now (); var fileReadTime = 0 setTimeout (function () {var delay = Date.now ()-timeoutScheduled; console.log (`setTimeout ${delay} ms have passed since I was sheculed`); console.log ('fileReaderTime', fileReadTime-timeoutScheduled);}, 10) SomeAsyncOperation (function () {fileReadtime = Date.now (); while (Date.now ()-fileReadTime)
< 20) {}}); 执行过程: setTimeout和readFile先后加入io setTimeout执行进入io;(需要10ms) readfile执行,也进入io;(需要2ms) 2ms之后, redfile已经读取完毕,加入poll队列,此时poll为空,执行someAsyncOperation回调; 由于此回调有while,这里阻塞20ms;执行完为22ms 在10ms时,setTimeout不能执行,因为js是单线程,setTimeout一直被阻塞 执行完之后(22ms以后),poll 进入空闲状态 event loop检查timer,setTimeout回调; 执行结果: readFile执行22ms setTimeout执行22ms之后 执行代码2 var fs = require('fs');var path = require('path');function someAsyncOperation(callback) { // 花费9ms fs.readFileSync('./read.txt', callback);}var timeoutScheduled = Date.now();var fileReadTime = 0;setTimeout(function() { var delay = Date.now() - timeoutScheduled; console.log(`setTimeout ${delay} ms have passed since I was sheculed`); console.log('fileReaderTime', fileReadTime - timeoutScheduled);}, 5);someAsyncOperation(function() { fileReadtime = Date.now(); while (Date.now() - fileReadTime < 20) {}}); 执行结果 setTimeout执行:5ms readFile执行9 ~ 29ms 执行代码3 在nodejs中,setTimeout(fn,0) === setTimeout(fn,0) 在浏览器中,setTimeout(fn,0) === setTimeout(fn,4) setImmediate(() =>{console.log ('setImmediate')}, 0) setTimeout (() = > {console.log (' setTimeout')}, 0) / the order of execution of setTimeout and setImmediate is uncertain / / because the startup of event loop also takes time, and it may have exceeded 1ms when it reaches the poll stage. In this case, setTimeout will first execute const fs = require ('fs'); const path = require (' path') Fs.readFile (path.resolve (_ dirname,'/ read.txt'), () = > {setTimeout (()) = > {console.log ('setTimeout');}, 0); setImmediate (() = > {console.log (' setImmediate');}, 0);}); / / the execution order is determined, setImmediate,setTimeout
Execution process:
Execute fs. There is no timer and setImmediate in the first round of main line.
Assuming that readFile needs 2ms, execute callback
Entering check,setImmediate from poll will be called first.
In the second round of timer, setTimeout is executed
This is the answer to the question about how to realize the event cycle in nodejs. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.