handle https file response errors

Problem

How would I handle a situation where the file does not exist on the server, or is unable to connect with the server to get the file?

As of the code below, the file download still occurs, and the file is empty.

var https = require('https');
var fs = require('fs');
var exec = require('child_process').exec;
var file = fs.createWriteStream('mediaserver_setup.exe');
var len = 0;
var req = https.get(url + 'appdata/update_setup.exe', function (res) {
  if (res.statusCode === 404) {
    alert('problem with request:');
  }
  res.on('data', function (chunk) {
    file.write(chunk);
    len += chunk.length;
    var percent = (len / res.headers['content-length']) * 100;
    progressLoading.val(percent);
  });
  res.on('end', function () {
    setTimeout(function () {
      file.close();
    }, 500);
  });
  file.on('close', function () {
    win.close();
    exec('update_setup.exe');
  });
});
req.on('error', function (err) {
  alert('problem with request: ');
});
Problem courtesy of: Jeff

Solution

Use the error event for requests, or check the status code of the response:

var https = require('https');
var req = https.get(options, function(res) {
  // use res.statusCode
  if (res.statusCode === 404) {
    // example for checking 404 errors
  }
});

req.on('error', function(err) {
  // an error has occurred
});
Solution courtesy of: hexacyanide

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.