处理https文件响应错误

时间:2013-10-11 17:23:07

标签: javascript node.js http stream node-webkit

如何处理服务器上不存在文件或无法与服务器连接以获取文件的情况?

截至下面的代码,仍然会发生文件下载,文件为空。

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

1 个答案:

答案 0 :(得分:0)

对请求使用error事件,或检查响应的状态代码:

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