What are the differences between event-driven and thread-based server system?

I wonder.Node.js works as event-driven.And İts have a thread.But How does it? Does not work the other thread behind,while A thread listening to port?if so, isn't this thread-based? I don't understand to difference between event-driven and thread-based.

What is the better than thread-based? What is the logic of it?
Which one and why?

The difference might be described as follows (with some simplification):

  • in "thread driven" runtimes, when request comes in, a new thread is being created and all the handling is being done in that thread.

  • in "event driven" runtimes, when request comes in, the event is dispatched and handler will pick it up. When? In Node.js there is a "event loop", which basically loops over all the pieces of code that needs to be executed and executes them one by one. So the handler will handle the event once event loop invokes it. The important thing here is that all the handlers are being called in the same thread - event loop doesn't have a thread pool to use, it only has one thread.

Outcome is that if in "event driven" model, handler will take a very long time to finish (i.e. by having a computantionally intensive for loop inside), no other request will be handled during that time, because event loop will not invoke the next handler before the current one completes. That's usually not an issue because of asynchronous nature of Javascript.

On the other hand, in "thread driven" model, if the handler blocks (i.e. in Java by calling Thread.sleep()), it won't hurt other threads much. Unfortunately, creating new thread isn't cheap and if you need to handle thousands of concurrent connections, it might become a burden. That's why Node.js is considered fast - no matter how many connections you handle, there's only one thread 1.

It's alos important to note that writing asynchronous code is possible in most of the runtimes. It has become most widely used in Node.js though, because of the nature of Javascript. Thanks to that virtually every library you use in Node will be asynchronous.

See this article (and pictures) for an explanation of event loop.

1 Of course there is more that one thread in Node.js process, some of them are related to I/O. But your app logic is handled in one thread.