Merge remote branch 'origin/v0.4'
[platform/upstream/nodejs.git] / benchmark / http_simple.js
1 path = require("path");
2 exec = require("child_process").exec;
3 http = require("http");
4
5 port = parseInt(process.env.PORT || 8000);
6
7 console.log('pid ' + process.pid);
8
9 fixed = ""
10 for (var i = 0; i < 20*1024; i++) {
11   fixed += "C";
12 }
13
14 stored = {};
15 storedBuffer = {};
16
17 var server = http.createServer(function (req, res) {
18   var commands = req.url.split("/");
19   var command = commands[1];
20   var body = "";
21   var arg = commands[2];
22   var n_chunks = parseInt(commands[3], 10);
23   var status = 200;
24
25   if (command == "bytes") {
26     var n = parseInt(arg, 10)
27     if (n <= 0)
28       throw "bytes called with n <= 0"
29     if (stored[n] === undefined) {
30       console.log("create stored[n]");
31       stored[n] = "";
32       for (var i = 0; i < n; i++) {
33         stored[n] += "C"
34       }
35     }
36     body = stored[n];
37
38   } else if (command == "buffer") {
39     var n = parseInt(arg, 10)
40     if (n <= 0) throw new Error("bytes called with n <= 0");
41     if (storedBuffer[n] === undefined) {
42       console.log("create storedBuffer[n]");
43       storedBuffer[n] = new Buffer(n);
44       for (var i = 0; i < n; i++) {
45         storedBuffer[n][i] = "C".charCodeAt(0);
46       }
47     }
48     body = storedBuffer[n];
49
50   } else if (command == "quit") {
51     res.connection.server.close();
52     body = "quitting";
53
54   } else if (command == "fixed") {
55     body = fixed;
56
57   } else {
58     status = 404;
59     body = "not found\n";
60   }
61
62   // example: http://localhost:port/bytes/512/4
63   // sends a 512 byte body in 4 chunks of 128 bytes
64   if (n_chunks > 0) {
65     res.writeHead(status, { "Content-Type": "text/plain",
66                             "Transfer-Encoding": "chunked" });
67     // send body in chunks
68     var len = body.length;
69     var step = ~~(len / n_chunks) || len;
70
71     for (var i = 0; i < len; i += step) {
72       res.write(body.slice(i, i + step));
73     }
74
75     res.end();
76   } else {
77     var content_length = body.length.toString();
78
79     res.writeHead(status, { "Content-Type": "text/plain",
80                             "Content-Length": content_length });
81     res.end(body);
82   }
83
84 });
85
86 server.listen(port, function () {
87   console.log('Listening at http://127.0.0.1:'+port+'/');
88 });
89
90 process.on('exit', function() {
91   console.error('libuv counters', process.uvCounters());
92 });