Last active
December 27, 2019 06:26
-
-
Save boydaihungst/28e9bae189a22eb4ad350d2a22f693ed to your computer and use it in GitHub Desktop.
Demo request download timeout
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const request = require('request'); | |
| const progress = require('request-progress'); | |
| const fs = require('fs'); | |
| function download(url) { | |
| var timeout; | |
| const rq = request | |
| .get(url) | |
| .on('connect', function(req, cltSocket, head) { | |
| // Set timeout khi vừa connect | |
| timeout = setTimeout(() => { | |
| request.abort(); | |
| }, 10000); | |
| }) | |
| .on('data', function(chunk) { | |
| clearTimeout(timeout); | |
| timeout = setTimeout(() => { | |
| rq.abort(); | |
| }, 10000); | |
| }) | |
| .on('abort', function() { | |
| console.log('aborted'); | |
| clearTimeout(timeout); | |
| }) | |
| // Event khi request kết thúc (Khi error, tải thành công hoặc là abort) | |
| .on('end', function() { | |
| console.log('end'); | |
| clearTimeout(timeout); | |
| }); | |
| /** | |
| * Mỗi lần tải được 1 phần nó sẽ chạy vào event này. | |
| * { | |
| time: { elapsed: 4.003, remaining: 95.767 }, | |
| speed: 10768682.23832126, | |
| percent: 0.04012217380482315, => phần % đã tải | |
| size: { total: 1074394304, transferred: 43107035 } => total: độ lớn file | |
| } | |
| */ | |
| progress(rq, {}).on('progress', function(state) { | |
| console.log(state); | |
| // length = state.size.total; | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment