Is the javascript node environment solitary, or is everything happening at the same time? Or (more likely) none of these statements explain what happens to node.
I am new to node and trying to understand how it handles callbacks. My googling on this issue did not turn out to be fruitful, and it seems that several audiences use terms such as "flows, blocking and single-threaded" with difference contexts for each audience, and I do not have enough experience working with node to correctly parse what I'm reading.
From what I read, the node javascript runtime, like the browser, is single-threaded. That is, despite the fact that everything is developed around asynchronous callbacks, everything happens in a deterministic order, and there are never two threads that change the same variable or run statements at the same time. I also read this that the node user programmer does not have to worry about locking semantics.
If I'm in a browser and use one of the popular javascript libraries to set a callback to a non-dom-event-handler, something like
console.log("Here"); $.each([1,2,3],function(){ console.log("-- inside the callback --"); }); console.log("There");
My conclusion is consistent
Here
However, if I do something similar with a callback in node js (by running it as a shell script from the command line)
var function example() { var fs = require('fs'); console.log("Here"); fs.readdir('/path/to/folder', function(err_read, files){ console.log('-- inside the callback --'); }); console.log("There"); for(var i=0;i<10000;i++) { console.log('.'); } } example(); console.log("Reached Top");
I consistently (apparently see "not much experience" above) get these results
Here There . . (repeat 10,000 times) Reached Top
That is, node terminates the execution of the example function before calling the callback.
Is this deterministic behavior in node? Or there are times when a callback will be called before the example function completes? Or will it depend on the implementation in the library with a callback?
I understand that the idea of a node is to write event-based code, but I'm trying to figure out what the node really does, and what behavior you can rely on and what not.