2
今天,当我尝试实现在NodeJ中使用异步/同步I/O方法的示例时,我遇到了一个奇怪的问题。当我试图用ab
发送请求,我在异步方法来获取此错误:异步文件读取中的EMFILE错误
{ [Error: EMFILE, open 'sample.txt'] errno: 20, code: 'EMFILE', path: 'sample.txt' }
但在同步模式相同的功能运作良好,没有任何错误。
这是我运行测试ab
命令:
ab -n 10000 -c 1000 -vhr http://localhost:8080/
这里是我的两个代码:
异步:
http.createServer(function (req, res) {
fs.readFile('sample.txt', function (err, data) {
if(err) {
res.writeHead(500, {'Content-Type': 'text/plain'});
res.end();
console.log(err);
} else {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(data);
}
});
}).listen(8080, '127.0.0.1');
同步:
http.createServer(function (req, res) {
var fileOutput = fs.readFileSync('sample.txt').toString();
if(!fileOutput) {
res.writeHead(500, {'Content-Type': 'text/plain'});
res.end('Error in reading the file.');
} else {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(fileOutput);
}
}).listen(8081, '127.0.0.1');
这是怎么回事?使用异步方法有什么问题吗?
很好,看起来不错的解决方案。当我使用'fs.readFile'时,如何关闭链接? – 2013-04-25 12:25:56
您不能,您需要限制连接数或更好地增加您使用的系统的打开文件限制。 – Mustafa 2013-04-25 17:01:49