By rick 3 Comments
I'm going to preface this blog entry with a message to seasoned developers who would quickly be wondering why I'm glossing over a ton of stuff. I'm writing this post for a audience that knows enough to be dangerous but lets guys and girls like you do the heavy lifting. You can move on to the next blog in your daily reading list. You should know all this stuff.
There are no threads in nodeJS but it is basically multithreaded. Yes I said that. Its not multithreaded in the way Java or ASP.NET is. Those environments use a preemptive threading model. Programmers don't have to think about threading in that model though they very well do need to know that they are in a multithreaded environment. The hard part of that model is making sure that two threads aren't using the same resource at the same time. That is much harder than it seems and its one of the hardest things for any programmer to get right.
Here's a simple closure example
You'll notice that function is provided as a parameter to the fileSystem.readFile function. This function will be executed when the data from the file has been read. A lot of time had passed between the time that the function fileSystem.readFile was called and when the closure was called. In that time, nodeJS let other tasks run. In any other environment the server stalled while it waited for the file to be read. No other requests could be processed. The above example is fairly straightforward but let me show you another example where data is read from a file, written to a database and the the file was cleared out.
You see here where it starts getting a little hard to follow. Its inception! Or an episode of Pimp My Back End. (Yo dawg, I heard you like functions so I put a function inside of your function inside of another function). Even this example is fairly simple compared to some of the nodeJS code I've come across. Does that look like any frontend code you've ever come across. Probably not. And this is where nodeJS will take you and your previously frontend only developers over the cliff. This kind of thing is what nodeJS code is all about. Are you scared yet?
Tomorrow I'll dive further into why nodeJS so cool and also do my best to scare the hell out of you so you'll go running when someone suggests you use it.