title: How can I speedup node.js File operations?
body: <p>In my project, a client will request to download a file from server with an id. I have to perform the following operations:</p>
  
  <ul>
  <li>Validate the id from mongoDb</li>
  <li>Check extension</li>
  <li>Check File exists or not</li>
  <li>Read the file and write content to response</li>
  </ul>
  
  <p>I am using the following code for checking file and sending the response.</p>
  
  <pre><code>fs.exists(filename, function(exists) {
    if (!exists) {
      res.writeHead(404, '', {
        "Content-Type" : "text/plain"
      })
      res.write("404 Not Found\n");
      res.end();
      return;
    }
    fs.readFile(filename, "binary", function(err, file) {
      if (err) {
        res.writeHead(500, '', {
          "Content-Type" : "text/plain"
        })
        res.write(err + "\n");
        res.end();
        return;
      }
      res.setHeader("Pragma", "public");
      res.setHeader("Cache-Control: private, max-age=3600");
      res.setHeader("Transfer-Encoding:  chunked");
      res.setHeader("Range:  chunked");
      res.writeHead(200, '', {
        "Content-Type" : contentType
      });
      res.write(file, "binary");
      res.end(file, "binary");
    });
  });
  </code></pre>
  
  <p>Within a few milliseconds, the client will request hundreds of files. The supporting file types are image,audio or video.</p>
  
  <p>When there are lots of files in the folder, node.js is taking too much time to download the file. How can I improve the performance?</p>