In this section I will try to present philosophical aspects behind NodeJS covering design principles and programming techniques inspired its development.
- Hollywood Principle: “Don’t call us we will call you”. To understand this here’s a small story – a struggling actor goes to some director and ask for role, currently the director don’t have any suitable assignment for him, and he don’t want to be bothered again and again, so he asked actor to leave his contact detail to his assistant and says – “don’t call me I will call you if some assignment is there”. This principle initiated the callback mechanism, whereby one task depending on other task for some processing, simply submit request along with a callback method/function to be called by other task when result is available. This way tasks do not block important resources like ‘thread’ in waiting.
- Asynchronous Call: To understand this first understand that ‘asynchronous’ is the state of being ‘not synchronised’; synchronous process generally wait for final result to be calculated whether success or failure. In asynchronous call you submit your request along with callback handler that must be triggered when result is prepared and returned, your process doesn’t wait rather continue with its flow. To achieve this ofcourse threads are required but that will be handled by nodejs for developer its single threaded programming model.
executeQuery("select empid from employee", resultHandler(data))
Here your resultHandler is a callback handler.
Please see http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop/ for more detail on single thread model.
executeQuery("select empid from employee", resultHandler(data));
Here you can see displaying process running info to user is called after db call is made; and this will display process window because your execution flow is not blocked by the call of ‘executeQuery’, also you are not doing anything special to achieve this it will be handled out of the box.
Conclusion: Hollywood principle is the key design principle behind non-blocking implementation, and callback and event loop is the technique to achieve asynchronous/non-blocking behaviour.
- Node is designed to be used for applications that are heavy on input/output, but light on computation (computation intensive task should be delegated out of node).
- To leverage single thread programming model (for developers) to achieve simplicity, while handling complex multithreading in the background out of the box.
- To reduce memory overhead that is inherent in request per thread model.
- Learning Node, O’REILLY, Shelley Powers.