Getting server info using nodejs

Getting server information using nodejs is very easy especially using the os module.

Wrote a simple script to fetch hostname, loadavg, uptime, freemem, totalmem, cpus, type, release, networkInterfaces, arch, platform, getNetworkInterfaces from the server where the node is running.

Below is the code to get the server info using nodejs :

var http = require('http');
var os = require('os');
var url = require('url');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  var call = url.parse(req.url).pathname.replace(/.*\/|\.[^.]*$/g, '');
  if( call === "all"){
       Object.keys(os).map(function(method) { res.write(method+":"+JSON.stringify(os[method](),2,true))+","; })
  }
  else{
      try{
          var resu = os[call]();
          res.write(JSON.stringify(resu),'utf8');
      }
      catch(e){
          res.end("Sorry, try on of : "+Object.keys(os).join(", "));
      }
  }
  res.end();
}).listen(1337, "localhost");
console.log('Server running at http://localhost:1337/');

After executing the above, one can just curl to get the info, say for example one needs to details of the CPUS on the server, she could curl http://localhost:1337/cpus and the output would be like :

[{
    "model": "Intel(R) Core(TM)2 Quad CPU    Q6600  @ 2.40GHz",
    "speed": 2400,
    "times": {
        "user": 63400,
        "nice": 80120,
        "sys": 35010,
        "idle": 6422450,
        "irq": 0
    }
}, {
    "model": "Intel(R) Core(TM)2 Quad CPU    Q6600  @ 2.40GHz",
    "speed": 2400,
    "times": {
        "user": 72900,
        "nice": 39950,
        "sys": 29920,
        "idle": 6574560,
        "irq": 0
    }
}, {
    "model": "Intel(R) Core(TM)2 Quad CPU    Q6600  @ 2.40GHz",
    "speed": 2400,
    "times": {
        "user": 51660,
        "nice": 58230,
        "sys": 27680,
        "idle": 6518900,
        "irq": 0
    }
}, {
    "model": "Intel(R) Core(TM)2 Quad CPU    Q6600  @ 2.40GHz",
    "speed": 2400,
    "times": {
        "user": 51980,
        "nice": 57470,
        "sys": 23640,
        "idle": 6509680,
        "irq": 0
    }
}]

To get all details, one could just do an ajax call or a simple curl to localhost/all indeed 'localhost', will be the IP of your server in the code and the curl call.

This particular process as an independent unit might not be very useful, but as a helper method definitely is!

Share this