0

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

在下面的代码中,文件下载仍然发生,并且文件是空的。

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

1 回答 1

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
});
于 2013-10-11T17:26:50.930 回答