web_server.js 1.2 KB

12345678910111213141516171819202122232425262728293031
  1. // A simple web server that generates dyanmic content based on responses from Redis
  2. var http = require("http"), server,
  3. redis_client = require("redis").createClient();
  4. server = http.createServer(function (request, response) {
  5. response.writeHead(200, {
  6. "Content-Type": "text/plain"
  7. });
  8. var redis_info, total_requests;
  9. redis_client.info(function (err, reply) {
  10. redis_info = reply; // stash response in outer scope
  11. });
  12. redis_client.incr("requests", function (err, reply) {
  13. total_requests = reply; // stash response in outer scope
  14. });
  15. redis_client.hincrby("ip", request.connection.remoteAddress, 1);
  16. redis_client.hgetall("ip", function (err, reply) {
  17. // This is the last reply, so all of the previous replies must have completed already
  18. response.write("This page was generated after talking to redis.\n\n" +
  19. "Redis info:\n" + redis_info + "\n" +
  20. "Total requests: " + total_requests + "\n\n" +
  21. "IP count: \n");
  22. Object.keys(reply).forEach(function (ip) {
  23. response.write(" " + ip + ": " + reply[ip] + "\n");
  24. });
  25. response.end();
  26. });
  27. }).listen(80);