Afshin Mehrabani
Afshin Mehrabani

Reputation: 34987

EMFILE error in Async file reading

Today when I tried to implement an example of using async/sync I/O methods in NodeJs, I faced an strange problem. When I'm trying to send requests with ab, I get this error in Async method:

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

But the same functionality in Sync mode works well, without any errors.

This is my ab command for running the test:

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

Here is my both codes:

Async:

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

Sync:

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

What's the matter? Is there any problem in using Async methods?

Upvotes: 2

Views: 1496

Answers (1)

Mustafa
Mustafa

Reputation: 10413

In both you do the following:

1 - Open file. 2 - Read file. 3 - Close file. 4 - Send the response.

However, in sync you always do the following: (1-2-3) in one statement. They are atomic. You may be opening many files before sending them, but all the time you open it and close it. However, in async, they are not atomic and any of them can be hapening at given time. So, in async, it is more likely to recieve the requests, open the files, but before reading & sending them, you actually opened many more files. Shortly, in sync, you open-read-close-send the data, in async you open-open-open-open-read-open-open-close-open-send-open (these events order depends on the arrival time of the data and the disk read speeds).

Upvotes: 3

Related Questions