forked from hakobera/nvmw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fget.js
75 lines (66 loc) · 1.59 KB
/
fget.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
main(WScript.Arguments);
/**
* Main function
* @param {Object} args Command line arguments
*/
function main(args) {
if (args.length < 2) {
log('useage: CScript fget.js [url] [filname]');
WScript.Quit(1);
}
var url = args(0)
, filename = args(1);
var completed = false;
downloadFile(url, filename, function(err) {
if (err) {
log(err.message);
} else {
log('Done');
}
completed = true;
});
while (!completed) {
WScript.Sleep(1000);
}
}
/**
* Log output to console.
* @param {String} message
*/
function log(message) {
WScript.Echo(message);
}
/**
* Download file from specified URL
*
* @param {String} url Url to download
* @param {String} filename Filename to save
* @param {Function} callback Callback function when download is completed or failed
*/
function downloadFile(url, filename, callback) {
var xhr = WScript.createObject('Msxml2.XMLHTTP')
, ostream = new ActiveXObject("Adodb.Stream");
log('Download from ' + url + ', and save it as ' + filename);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
ostream.type = 1/*adTypeBinary*/;
ostream.open();
ostream.write(xhr.responseBody);
ostream.savetofile(filename, 2/* adSaveCreateOverWrite */);
callback();
} else {
callback(new Error(xhr.status + ' ' + xhr.statusText));
}
xhr = null;
ostream = null;
}
}
try {
xhr.open('GET', url, true);
xhr.send(null);
} catch (e) {
callback(new Error('URL may be invalid'));
xhr.abort();
}
}