Merge remote-tracking branch 'origin/v0.6'
[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 if (command == "echo") {
58     res.writeHead(200, { "Content-Type": "text/plain",
59                          "Transfer-Encoding": "chunked" });
60     req.pipe(res);
61     return;
62
63   } else {
64     status = 404;
65     body = "not found\n";
66   }
67
68   // example: http://localhost:port/bytes/512/4
69   // sends a 512 byte body in 4 chunks of 128 bytes
70   if (n_chunks > 0) {
71     res.writeHead(status, { "Content-Type": "text/plain",
72                             "Transfer-Encoding": "chunked" });
73     // send body in chunks
74     var len = body.length;
75     var step = ~~(len / n_chunks) || len;
76
77     for (var i = 0; i < len; i += step) {
78       res.write(body.slice(i, i + step));
79     }
80
81     res.end();
82   } else {
83     var content_length = body.length.toString();
84
85     res.writeHead(status, { "Content-Type": "text/plain",
86                             "Content-Length": content_length });
87     res.end(body);
88   }
89
90 });
91
92 server.listen(port, function () {
93   console.log('Listening at http://127.0.0.1:'+port+'/');
94 });
95
96 process.on('exit', function() {
97   console.error('libuv counters', process.uvCounters());
98 });