From here i have found that node.js
implements non-blocking i/o model. But i don't understand how.
As javascript is single threaded. How can a single thread do i/o operations and simultaneously executing the further process.
From here i have found that node.js
implements non-blocking i/o model. But i don't understand how.
As javascript is single threaded. How can a single thread do i/o operations and simultaneously executing the further process.
Share Improve this question edited Feb 28, 2016 at 20:37 bakkal 55.4k12 gold badges136 silver badges113 bronze badges asked Aug 20, 2013 at 11:05 codeofnodecodeofnode 18.6k29 gold badges88 silver badges146 bronze badges3 Answers
Reset to default 10It is true that operations such as sleep will be blocking the thread. But I/O events can indeed be asynchronous.
Node.js uses an event loop for this. An event loop is “an entity that handles and processes external events and converts them into callback invocations”
Whenever data is needed nodejs registers a callback and sends the operation to this event loop. Whenever the data is available the callback is called.
http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop/ for more info
The I/O that is handled by node.js
is multithreaded internally.
It is the programming interface that is single threaded and asynchronous.
Ryan Dahl: Original Node.js presentation at JSConf 2009 (Ryan is the creator of Node.js)
This video will answer your question.
The essence of JavaScript(v8) is event callbacks (button onclick="functions()" etc). That's how the I/O is multithreaded. We still have to write our code to not have blocking I/O by only writing callbacks; otherwise the code will wait on db.query responses and be blocking before executing the next line of code.