Node.js Event loop

前端 未结 5 1643
借酒劲吻你
借酒劲吻你 2020-11-30 20:10

Is the Node.js I/O event loop single- or multithreaded?

If I have several I/O processes, node puts them in an external event loop. Are they processed in a sequence

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 20:46

    you have to know first about nodeJs implementaion in order to know event loop.

    actually node js core implementation using two components :

    • v8 javascript runtime engine

    • libuv for handlign non i/o blocking operation and handling threads and concurrent operations for you;

    with the javascript you can actually write code with one thread but this means not that your code execute on the one thread although you can execute on multiple thread s using clusters in node js

    now when you want to execute some code like :

    let fs = require('fs');
    fs.stat('path',(err,stat)=>{
      //do something with the stat;
       console.log('second');
       
    });
    
    console.log('first');

    • the execution of this code at high level is like this: first the v8 engine run this code and then if there is no error everything is good then it looks for the it try to run it run line by line when it gets to the fs .stats this is a node js api very similar to the web apis like setTimeout that the browser handle it for us when it encounter to the fs.stats it is pass the code to the libuv components with a flag and pass your callback to the event queue then the libuv you execute your code during the operation and when its done just send some signal and then d the v8 execute your code az a callback you set on the queue but it always check for the stack is empty then go for the your code on the queue # always remember that !

提交回复
热议问题