-2

I just started learning node.JS. And I found that there are two models: blocking and nonblocking.

I know non-blocking can do I/O requests at the same time and blocking model has to wait for I/O response and then do the other I/O request.

However, there might still be I/O interrupt, if we do two I/O requests at the same time. So I am kind of confused here.

So my questions are:

  1. It looks like non-blocking model is definitely better than blocking one, then why we need blocking model?

  2. Why there is no I/O interrupt with non-blocking model?

Will
  • 133
  • 3
  • 15
  • Welcome, please read [tour] then [ask] then [mcve]. Also, there are 3,000+ existing results on SO for "node.js blocking" did you read any of them? – Dave S Jan 15 '18 at 23:17
  • 1
    @DaveS Sorry for asking duplicate question and I flagged it to close. I am kind of new here so when I typed the questions there and it did not come up with any results for some reason, I thought there was no answer. I just searched it again and it did have result this time. Anyway, thanks for the remind. – Will Jan 15 '18 at 23:39
  • We were all new here once :) . Search here and with Google are always worth trying since the existing questions might give you the answer without needing to wait, and give much more info than a quick answer to your own question. – Dave S Jan 15 '18 at 23:42

1 Answers1

0

Blocking I/O code is easier to write unless you start doing it with multiple threads in which case it may no longer be easier. When I write a one-time use script (not a server) such as a script to process a bunch of files on my hard drive, I will sometimes use the synchronous versions of file I/O such as fs.readFileSync() because it's just simpler and easier to write. FYI, I never use synchronous I/O in a server (other than at server initialization time) because it wrecks the scalability of the server when used in real time requests.

As an example of how synchronous I/O is simpler, require() uses synchronous file I/O. If it didn't, then initializing a module that had multiple external modules to load (some of which depend on each other) could get a lot more complicated than just lining up four require() statements on successive lines.

Non-blocking I/O code requires learning new techniques in order to serialize multiple I/O requests (learning callbacks or promises), but allows you to write code that scales really well without having to worry about thread synchronization and without risking the bugs that often occur in multi-threaded code.

jfriend00
  • 683,504
  • 96
  • 985
  • 979