Websocket URL routing (specifying MQTT subscription topic by URL)

My previous example Node.js, MQTT and Websockets showed the use of a websocket to broadcast messages from a subscribed MQTT topic, however the topic was hard coded and the messages broadcast to all who connected. The example below uses the same client side script to connect but allows the MQTT topic to be specified in the URL and only broadcasts to the individual client. Now to subscribe to a topic “test” the websocket address would be ws://<ip>/test.

/* Include required libraries */
var util   = require('util'),
    sys = require('sys'),
    url = require('url'),
    ws = require('websocket-server'),
    spawn = require('child_process').spawn,

    /* Create websocket server */
    server = ws.createServer({debug: true});

/*
 * Add listener for web socket connections
 */
server.addListener('connection', function(conn){

/*
 * Ceate call to mosquitto_sub cli client
 * to subscribe on topic specificed by the url
 *
 * substr(1) removes intial / from path
 */
mosq = spawn('mosquitto_sub',['-t',conn._req.url.substr(1)]);

/*
 * Bind an event to stdout to get output from mosquitto_sub
 * and publish it to the websocket
 */
mosq.stdout.on('data', function (data) {
    /*
     * Brodcast the MQTT message straight back
     * out on the websocket
     */
    server.send(conn.id, data)

    /* Log the message to the console */
    console.log('' + data);
    });

    /*
     * Bind an event to stderr so we can see any
     * errors that cause mosquitto_sub to crash
     */
    mosq.stderr.on('data', function (data) {
    console.log('error: ' + data);
    });

});

/* Start the websocket server listening on port 8000 */
server.listen(8000);