Event-Driven Programming with Node.js

Lately I have been playing a lot with Node.js and event-driven programming, and several ‘gotcha’ moments occurred. Below you’ll find of them.

Event-Driven Programming: As the name implies, a programming paradigm where the flow of the program is governed by events. There is a main loop monitoring things and triggering the appropriate callbacks.

Noje.js: Contrary to what some programmers think (I heard it a couple of times), Node.js is NOT a web server. Instead it’s a JavaScript runtime environment, which uses Google’s V8 engine to interpret JavaScript. It has an event-driven architecture capable of asynchronous I/O, which makes is quite suitable for web and real time applications.

Callbacks: A piece of code (usually a function) passed to another piece of code (usually another function, passed as an argument) to be executed at proper time. Useful when you want to specify how a function is supposed to execute part of its task (i.e. how to compare two numbers) or when you want your code to be executed once the function is done and the result available.

Functions as first-class citizens: In order for callbacks to work, functions need to be first-class citizens in the specific language. This means that they need to support all the operations that other entities support, including being passed as an argument.

Nested callbacks: If you need to do synchronous stuff with Node.js you might need to nest callbacks to achieve the desired result, and you can store functions inside variables to help. Example:

var updateQuery = function(value){
    client.query('UPDATE T_STATE SET value='+value,function(err,result){
        throw err;

client.query('SELECT value from T_STATE',function(err,result){
        throw err;
        var stateValue =  result.rows[0].value;              

Node.js and callbacks: Callbacks are everywhere in Node.js and related libraries (i.e., Express.js). Usually those callbacks handle error first and then execute the specific code.

Stack, Heap, Queue, Event Loop: JavaScript function calls get a stack frame on the stack (with arguments, local variables, etc.). Objects are allocated in the heap. When you call web APIs (e.g., XMLHttpRequest or setTimeout) those go in the queue (as messages). When events with listeners happen, they also go into the queue. Whenever the stack is free, the event loop will get the first message from the queue and put it on the stack for execution.

Useful resources:

Event-Driven programming with analogies
Understand the event loop

Leave a Reply

Your email address will not be published. Required fields are marked *