Now I’m starting to have fun with Nodejs. This is because the excellent tutorials from Node tuts and because WebStorm is awesome.
Let’s run it with Node:
Blocking vs non-blocking
This is an example of blocking code:
1 2 3 4
This will run line by line, and all other processes are blocked until its finished.
With Node, we should be writing non blocking code, like this:
1 2 3 4 5 6
The readFileSync accepts two parameters, the file to read and another function: the callback function. The callback function has 2 parameters, one that contains the error (if there is one) and one that contains the result.
We can also write the function like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
I think it’s more readable to add the callback function as a parameter and then we can omit ‘callback’ and use an anonymous function:
1 2 3 4 5 6 7
So this is the essence of Nodejs:
- stop writing threads and other procedural blocking code
- start writing asynchronous code
- in a third party lib the last parameter is the callback
- in a callback function the first parameter is the error, the second parameter is the result.