我正在尝试从某些URL下载视频,由于某些原因,下载有时会在视频完成之前停止-如在res.on('data', ...)
中,在响应之前将停止调用(使用https.get
)已经完成。我希望能够在给定的时间后检测到该问题并重试该请求,但是我很难获得它的工作代码。我希望能够以一种内置的方式来处理我所缺少的类似问题。我已经尝试过为请求设置超时并为响应设置超时,而这些似乎都不起作用。
当前尝试:
async function downloadVideo(send) {
try {
https.get(downloadUrl, res => {
let timerId;
res.on(`data`, (c) => {
clearTimeout(timerId);
timerId = setTimeout(() => {
res.destroy();
console.log(`retrying`, name);
downloadVideo(send);
}, 2000);
if (!throttle) {
send(`PercentDownloaded`, [
index,
100 * fileSize(filePath) / res.headers[`content-length`]
]);
throttle = true;
setTimeout(() => throttle = false, 500);
}
});
res
.pipe(fs.createWriteStream(filePath))
.on(`finish`, () => {
clearTimeout(timerId);
send(`Done`, index);
});
});
} catch (error) {
console.log(name, error);
send(`DownloadError`, index);
}
}