NOTE: CRT is excited to have Mark Lesswing, Chief Technology Officer and SVP of ITS at NAR, write a series of posts on his experiences with node.js. In the article below, Mark highlights some key differences between traditional server-side languages and node.js. Please note that this will be a pretty technical series and speaks to the diversity of topics CRT will cover. We will indicate when we have articles that are more technical as we post them. Thank you. – Chad
If you want to quickly grasp node.js, you must think in terms of events, just as you do in Javascript in the browser. This callback approach is a departure from the way things used to be done on the server-side. Traditionally, the name of the game was frameworks, scripting or object-oriented modules. Node.js works best if you abandon that thinking and model “thread-like” behavior; a scriptable asynchronous server.
Here is a quick comparison between traditional and event-based flow using pseudo code:
print “Start”
Open a File
print “File is Open”
for each line of the file …
print “Hello”
end of reading lines
close the file
print “File Closed”
print “Goodbye”
The output of this simple example, using a three line file in a tradition (synchronous) language, would be:
- Start
- File is Opened
- Hello
- Hello
- Hello
- File Closed
- Goodbye
Using something like Node.js (again pseudo code):
Print “Start”
Open a fileUpon opening, perform the following
print “File is open”For each line read, perform the following
print “Hello”
End reading a lineClose the File
End of opening processUpon closing the file
print “File Closed”
End of closing the filePrint “Goodbye’
The output with a synchronous processor, again on a three line file would be:
- Start
- Goodbye
- File is Open
- Hello
- Hello
- Hello
- File Closed
If you write Javascript, you will recognize this as event processing. It takes some time to get used to if you are used to traditional server-side languages. Opening files, reading and writing are all “events”, just as a button click is an event in a browser. One big difference is that you do not have to register “listeners” with Node.js. The Objects have throw events and you simply catch them with event handlers. Warning, you have to be aware of the scope of your variables. Notice the “Goodbye” is executed before the file is opened.
