在asynchronous文件读取中的EMFILE错误

今天,当我尝试实现在NodeJ中使用asynchronous/同步I / O方法的示例时,我遇到了一个奇怪的问题。 当我试图用ab发送请求时,在Async方法中出现这个错误:

 { [Error: EMFILE, open 'sample.txt'] errno: 20, code: 'EMFILE', path: 'sample.txt' } 

但同步模式下的相同function运行良好,没有任何错误。

这是我运行testing的ab命令:

 ab -n 10000 -c 1000 -vhr http://localhost:8080/ 

这是我的两个代码:

asynchronous

 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'); 

怎么了? 使用Async方法有什么问题吗?

在你做两件事:

1 – 打开文件。 2 – 读取文件。 3 – closures文件。 4 – 发送回应。

但是,在同步中,您总是在一个语句中执行以下操作:(1-2-3)。 他们是primefaces的。 在发送文件之前,您可能会打开许多​​文件,但是一直打开并closures文件。 但是,在asynchronous方面,它们不是primefaces的,在给定的时间内它们中的任何一个都可以开始。 所以,在asynchronous的情况下,更可能收到请求,打开文件,但在读取和发送它们之前,实际上打开了更多的文件。 不久,同步,你开读 – closures – 发送数据,在asynchronous你打开 – 开放 – 开放 – 开放 – 读取 – 开放 – 开放 – closures – 开放 – 发送 – 开放(这些事件的顺序取决于到达时间数据和磁盘读取速度)。