-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathserverAsyncCluster.js
68 lines (64 loc) · 2.85 KB
/
serverAsyncCluster.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*-----------------------------------------------------------------------------+
| Cluster/Async I/O Benchmark Version 2.0.0 |
+------------------------------------------------+----------------------------+
| Copyright 2014, Synthetic Semantics LLC | http://synsem.com/ |
| Copyright 2015-2017, Jace A Mogill | [email protected] |
| Released under the Revised BSD License | [email protected] |
+------------------------------------------------+----------------------------*/
var fs = require("fs");
var config = require('./config.json');
var http = require('http');
var url_module = require("url");
var async = require('async');
var cluster = require('cluster');
if (cluster.isMaster) {
for (var i = 0; i < config.nServers; i++)
cluster.fork();
return;
}
http.createServer(function (request, response) {
var key = url_module.parse(request.url).query.replace('key=','');
switch(request.method) {
case 'GET':
var asyncTasks = [];
for (var i = 0; i < config.nTimes; i++) {
asyncTasks.push(function (cb) {
fs.readFile(config.dataPath + key, 'utf8', function (err, data) {
if (err) return cb(err);
cb(null, JSON
.parse(data)
.sort()
.reduce(function (previousValue, currentValue) {
return previousValue + currentValue;
}) + data
)
})
})
}
async.parallel(asyncTasks, function (err, asyncResults) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end(JSON.stringify(asyncResults));
});
break;
case 'POST':
var postData = '';
request
.on('data', function (data) { postData += data; })
.on('end', function () {
fs.writeFile(config.dataPath + key, postData, 'utf8', function(err) {
if(err) {
response.writeHead(400, {'Content-Type': 'text/plain'});
response.end('Error: Unable to write file?' + err);
} else {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('success');
}
});
});
break;
default:
response.writeHead(400, {'Content-Type': 'text/plain'});
response.end("Error: Bad HTTP method: " + request.method);
}
}).listen(config.serverPort);
console.log('Asynchronous server is running., PID=', process.pid);