Php – What’s special about “non-blocking” node.js

node.jsPHPpythonweb-applicationsweb-development

In the short chapter, What is Node by McLaughlin, he writes:

"Node has no blocks, no threads competing for the same resource (Node
is happy to just let things happen however they happen), nothing that
has to start up upon request. Node just sits around waiting (quite
literally; unused Node responders are sleeping). When a request comes
in, it’s handled. This results in very fast code, without uber-
programmers writing the server-side behavior."

While I think he's picking on PHP here – from what I understand there isn't a way for PHP to not call up new references to its databases, files, etc, whenever any php page is loaded – is this really different than other web technologies? Consider Django/Flask for example or a simple Python threaded-server using builtin methods – is it really any different than the no-blocks advantages of Node? You run a program and it binds a socket, running the function only as needed. (Doesn't Java also do this?)

Best Answer

Let's immediately get the Turing-completeness disclaimer out of the way and say any language can probably approximate any runtime feature of any other language. Good? Good.

The main difference between the Node.js approach and a Python threaded-server (or a typical Java HTTP server implementation) is that Node.js is single threaded while the latter two are multithreaded. More specifically, the latter two will typically dedicate one thread per request. If, in the handling of that request, you need to do something slow like read from harddrive or connect to a remote database, the thread will sleep until the slow thing is done and the rest of the business logic is ready to proceed. In contrast, the Node.js approach is to schedule callbacks that are to be invoked once the slow thing is done; Node.js' single thread is never sleeping except if there are literally no requests to process.

The main difference between Node.js and PHP is that in Node.js, the code runs in a persistent context that exists as long as your Node.js server is running. So for example, if you write a value to a global variable in one request, and then read out the value of the global variable in another request, the read will see the value that was written by the write. In contrast, in PHP, a new context is created for each request, and so writes to globals in one request are lost when the script handling the request terminates.

Related Topic