NodeJS How Fun.
Wednesday, September 8th, 2010I have been playing around with nodejs for a few weeks now and I have to say its pretty amazing what one can do with it. I have been working on a node server that will host real-time queue information using web sockets. Yes I know your going to say web-sockets are only supported in Chrome, Firefox and Safari, Well I have to tell you if your still using IE for your internet experience you really missing out. With nodejs you can attach to child process and execute commands on the system and display them back to the browser. A great example of this is using iostat on linux/unix system. Below is the code for it.
var sys = require("sys"),
http = require("http"),
ws = require('./deps/node-websocket-server/lib/ws'),
fs = require("fs");
var iostat = require("child_process").spawn("iostat",["-w 1"]);
var httpServer = http.createServer();
var server = ws.createServer({debug:true},httpServer);
// Format iostat date
function format (data){
var output_data = data.toString();
console.log(output_data);
header = 'disk0 cpu load average';
if (output_data.match(header)){
console.log("ignore header");
}else{
var output_array = output_data.replace(/^\s+|\s+$/g,"").split(/\s+/);
for (var i=0; i < output_array.length; i++){
output_array[i] = parseFloat( output_array[i]);
};
output_hash = {
date:new Date(),
disk:{
kpt:output_array[0],
tps:output_array[1],
mbs:output_array[2]
},
cpu:{
us:output_array[3],
sy:output_array[4],
id:output_array[5]
},
load_average:{
m1:output_array[6],
m5:output_array[7],
m15:output_array[8]
}
}
return JSON.stringify(output_hash);
}
}
server.addListener("connection",function(conn){
console.log("opened connection: "+conn.id);
server.send(conn.id,"connected as:"+conn.id);
iostat.stdout.on('data',function(data){
console.log(typeof(data));
console.log('stdout: '+data);
console.log('stdout: '+format(data));
server.send(conn.id, format(data));
});
server.send(conn.id, "Connected as: "+conn.id);
});
server.addListener("close",function(conn){
console.log("closed connection: "+conn.id);
conn.broadcast("<"+conn.id+"> disconnected");
});
server.listen(9000);
This code allows you to stream iostat’s output over a http server on port 9000 to read by a client html file and js script. Its pretty neat because you can pass that information in to a graphing library like Protovis Graphing. With the addition of web-sockets that means you can have real time CPU information streaming to a web browser. Works great when you have systems where you really want to know how say a MySQL query is effecting the system itself. You should really give it a try.