我写了一个非常小的nodejs脚本。没什么好看的,只是听一个请求,生成一个108KB的大随机字符串,通过将其写入文件来执行i / o,然后从中读取。 最后,把它放回到响应流中。
我们的想法是将node.js功能与其他系统(如lamp / asp.net)进行对比,以便我开发一个Web应用程序:
//server.js
var http = require('http');
var server = http.createServer(handler);
function handler(request, response) {
//console.log('request received!');
response.writeHead(200, {'Content-Type': 'text/plain'});
s=""; //generate a random string of 108KB
for(i=0;i<108000;i++)
{
n=Math.floor(65 + (Math.random()*(122-65)) );
s+=String.fromCharCode(n);
}
//write s to a file
var fs = require('fs');
fs.writeFile("godspeed.txt", s, function(err) {
if (err) throw err;
//console.log("The file was saved!");
//read back from the file
fs.readFile('godspeed.txt', function (err, data) {
if (err) throw err;
result = data;
response.end(result);
});
}
);
}
server.listen(8124);
console.log('Server running at http://127.0.0.1:8124/');
以上工作正常,当我从浏览器打开它时返回字符串。但是,当我对此运行apache基准测试工具(总共有2000个请求和200个并发请求)时,大约911个请求显示为失败,这意味着我的代码有问题:
Concurrency Level: 200
Time taken for tests: 41.887 seconds
Complete requests: 2000
**Failed requests: 911**
你能帮我弄清楚我的代码有什么问题吗? (除了这些失败的请求之外,node.js在性能方面表现优异,考虑到与其他系统相比的总时间。)