title: Node.js and Request - limiting the file size of downloaded file
body: <p>I want to download a file with the Request library. It's pretty straightforward:</p>
  
  <pre><code>request({
      url: url-to-file
  }).pipe(fs.createWriteStream(file));
  </code></pre>
  
  <p>Since the URL is supplied by users (in my case) I would like to limit the maximum file size my application will download - let's say 10MB. I could rely on <code>content-length</code> headers like so:</p>
  
  <pre><code>request({
      url: url-to-file
  }, function (err, res, body) {
      var size = parseInt(res.headers['content-length'], 10);
  
      if (size &gt; 10485760) {
          // ooops - file size too large
      }
  }).pipe(fs.createWriteStream(file));
  </code></pre>
  
  <p>The question is - how reliable is this? I guess this callback will be called <em>after</em> the file has been downloaded, right? But than it's too late if someone supplies the URL of file which is 1 GB. My application will first download this 1 GB of a file just to check (in the callback) that this is too big.</p>
  
  <p>I was also thinking about good old Node's <code>http.get()</code> method. In this case I would do this:</p>
  
  <pre><code>var opts = {
      host: host,
      port: port,
      path: path
  };
  
  var file = fs.createWriteStream(fileName),
      fileLength = 0;
  
  http.get(opts, function (res) {
      res.on('data', function (chunk) {
          fileLength += chunk.length;
  
          if (fileLength &gt; 10485760) { // ooops - file size too large
              file.end();
              return res.end();
          }
  
          file.write(chunk);
      }).on('end', function () {
          file.end();
      });
  });
  </code></pre>
  
  <p>What approach would you recommend to <strong>limit download max file size</strong> without actually downloading the whole thing and checking it's size after all?</p>