如何处理服务器上不存在该文件或无法与服务器连接以获取文件的情况?
从下面的代码开始,文件下载仍然发生,并且文件为空。
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: ');
});
对请求使用 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
});