Understanding NodeJS & Non-Blocking IO

后端 未结 3 1954
春和景丽
春和景丽 2021-02-18 22:48

So, I\'ve recently been injected with the Node virus which is spreading in the Programming world very fast.

I am fascinated by it\'s \"Non-Blocking IO\" approach and hav

3条回答
  •  鱼传尺愫
    2021-02-18 23:16

    A similar question was asked and probably contains all the info you're looking for: How the single threaded non blocking IO model works in Node.js

    But I'll briefly cover your 3 parts:

    1.
    Lines 2 and 3 in a very simple form could look like:
          db.query(..., function(query_data) { ... });
          fs.readFile('/path/to/file', function(file_data) { ... });

    Now the function(query_data) and function(file_data) are callbacks. The functions db.query and fs.readFile will send the actual I/O requests but the callbacks allow the processing of the data from the database or the file to be delayed until the responses are received. It doesn't really "poll lines 2 and 3". The callbacks are added to an event loop and associated with some file descriptors for their respective I/O events. It then polls the file descriptors to see if they are ready to perform I/O. If they are, it executes the callback functions with the I/O data.

    I think the phrase "Everything runs in parallel except your code" sums it up well. For example, something like "Read HTTP parameters" would execute sequentially, but I/O functions like in lines 2 and 3 are associated with callbacks that are added to the event loop and execute later. So basically the whole point is it doesn't have to wait for I/O.

    2.
    Because of the things explained in 1., Node scales well for I/O intensive requests and allows many users to be connected simultaneously. It is single threaded, so it doesn't necessarily scale well for CPU intensive tasks.

    3.
    This paradigm has been used with JavaScript because JavaScript has support for callbacks, event loops and closures that make this easy. This isn't necessarily true in other languages.

    I might be a little off, but this is the gist of what's happening.

提交回复
热议问题