Node.js is a great tool for writing simple and efficient application servers with server-side JavaScript. A typical use case is a chat server, which might have a global data structure like this:

var CHAT = {
    channels: {
        '#general': {
            name: 'General',
            messages: [
            ],
            users: {
            }
        }
    }
};

In this structure, each channel exists as an object that holds the channel's name, its message history and the current user list.

The problem with in-memory data structures is that they are lost when restarting the Node.js application. During development this happens all the time.

An easy way to solve this is to have a background task that regularly saves the global state to a JSON text file:

var fs = require('fs');

function saveState() {
    fs.writeFile('/tmp/chat-state.json', JSON.stringify(CHAT));
    setTimeout(saveState, 10000);
}

setTimeout(saveState, 10000);

When starting up, the application can then check if this file exists and restore its state from it:

function loadState() {
    fs.readFile('/tmp/chat-state.json', function(err, data) {
        CHAT = JSON.parse(data);
    });
}

In a real world application you would probably want to add some error and sanity checking. Also, it might make sense to trigger a save whenever there is new activity, instead of a hardcoded 10 second interval.

Published 30.4.2011