verekia / js-stack-from-scratch

🛠️⚡ Step-by-step tutorial to build a modern JavaScript stack.
MIT License
20.09k stars 1.99k forks source link

Node event loop #173

Open ghost opened 7 years ago

ghost commented 7 years ago

Type of issue: feature suggestion

Chapter: Node

Please add an explanation of the node event loop.

It is important for people to understand that any long lived code will cause I/O starvation and service degradation.

verekia commented 7 years ago

Can you elaborate on I/O starvation and service degradation?

ghost commented 7 years ago

node is event driven. Events are processed in a loop, this is called the event loop.

As a part of the loop, your JavaScript code runs.

If your JavaScript code is CPU intensive, the rest of the events in the loop will take longer to be processed.

In an application, some events are time sensitive. e.g: TCP events may timeout if not processed in time, causing retransmissions and disconnections, errors and such.

CPU intensive tasks in node applications are usually operations that work over large inputs, usually large files. If you are processing each byte in a file: serialization, encryption, compression... you are more likely to cause delays in the event loop.

justinffs commented 7 years ago

I think Async Programming and Node Event loop are a bit too large of a topic to be covered by this tutorial and are a bit out side of the scope as well. Maybe a link to a source explaining it can be added some where. A quick google search found this but there might be a better one https://nodesource.com/blog/understanding-the-nodejs-event-loop/

Found this one as well https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/

ghost commented 7 years ago

I don't think it's safe for a programmer to implement functionality without being aware of the event loop constraints. This is not something you can safely disregard or be abstracted from.

All the behavior you implement needs to fit in ticks otherwise node cannot operate normally.