NodeJS: Check if an image only downloaded partway

前端 未结 1 1937
清歌不尽
清歌不尽 2021-01-26 01:13

I have created an image downloader in node.js. However when downloading images there is a chance the download will not complete, leaving me with a partially downloaded image (lo

相关标签:
1条回答
  • 2021-01-26 01:29

    The response event may be triggered prior to receiving all of the data. The pipe method can be used to write data to the destination stream as it becomes available, and should keep writing until there's no more. You can capture the status code and remove the file if the status is not 200 (otherwise it may contain an error response).

        ...
        let response = null;
        ...
        progress(request(url)
        ).on('progress', function(state){
            reportDownloadSpeed(state.speed); 
        }).on('end', function () { 
            if (response.statusCode != 200){
                console.log(`remove: ${filename}`);
                fs.unlinkSync(filename);
            }
        }).on('response', function(resp){
            response = resp;
        }).on('error', function(resp){
            reject(error);
        }).pipe(fs.createWriteStream(filename));
    
    0 讨论(0)
提交回复
热议问题