我正在做一个小脚本来下载带有节点的文件。我与网站的连接非常不稳定,通常会掉几次。我的想法是,如果连接在与以前相同的位置断开,则能够恢复下载。 我使用axios和progress-stream:
const download = (link, size, localPath, transferred = 0) => {
return new Promise((resolve, reject) => {
axios({
url: link,
method: 'GET',
responseType: 'stream'
})
.then(response => {
const writer = fs.createWriteStream(localPath);
const str = progress({
time: 100,
length: size,
transferred: transferred
});
str.on('progress', function(progress) {
console.log(progress);
});
response.data
.pipe(str)
.pipe(writer);
writer.on('finish', resolve);
writer.on('error', reject);
})
.catch(reject);
});
};
当断开连接并重新运行脚本时,我将参数“ transfered”传入文件当前未完成但下载从0开始的大小。 有没有办法在下载中断的地方开始下载?
答案 0 :(得分:0)
与@Nick LeBlanc mentioned一样,您需要使用Range
标头。
还请注意,fs.createWriteStream
默认情况下使用'w'
标志,该标志会在文件存在时将其截断。因此,您必须将其设置为'a'
。
const download = (link, size, localPath, transferred = 0) => {
return new Promise((resolve, reject) => {
axios({
url: link,
method: 'GET',
responseType: 'stream',
headers: {
Range: `bytes=${transferred}-`
}
})
.then(response => {
const writer = fs.createWriteStream(localPath, {flags: 'a'});
const str = progress({
time: 100,
length: size,
transferred: transferred
});
str.on('progress', function(progress) {
console.log(progress);
});
response.data
.pipe(str)
.pipe(writer);
writer.on('finish', resolve);
writer.on('error', reject);
})
.catch(reject);
});
};