-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathloadApi.promise.js
More file actions
82 lines (70 loc) · 2.28 KB
/
loadApi.promise.js
File metadata and controls
82 lines (70 loc) · 2.28 KB
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
76
77
78
79
80
81
82
/**
* Created by Willam Yang on 11/5/2015.
*/
'use strict';
var fs = require('fs'),
Promise = require('bluebird'),
superagent = require('superagent'),
cheerio = require('cheerio');
var load = module.exports = function (url) {
function get(url, autoReload, maxReloadTime) {
return new Promise(function (resolve) {
var count = 0;
console.log('Get from : ' + url);
function _get(url) {
superagent.get(url)
.end(function (err, res) {
if (err) {
console.log(err.code);
if (autoReload && count < maxReloadTime) {
count++;
console.log('Reload(' + count + ') : ' + url);
_get(url);
} else {
console.log('Auto reload time exceed!');
}
} else {
resolve(res);
}
});
}
_get(url);
})
}
function getModules(res) {
return new Promise(function (resolve) {
var $ = cheerio.load(res.text);
// saveFile('index.html', res.text);
var all = $('[href]');
for (var i in all) {
var attrs = all[i].attribs;
if (attrs) {
var href = attrs.href;
if (href && !href.match(/^https:|^http:/)) {
resolve(url + href, false);
}
}
}
});
}
function save(res) {
var $ = cheerio.load(res.text);
$('img').remove();
$('script').remove();
saveFile(res.req.path.replace('/docs/latest-v0.12.x/',''), $.html());
}
function saveFile(path, htmlStr) {
fs.writeFile(path, htmlStr, function (err) {
if (err) {
console.info(err);
} else {
console.log(path + ' save success!')
}
});
}
return get(url, true, 10)
.then(getModules)
.then(get)
.then(save);
};
load('https://nodejs.org/docs/latest-v0.12.x/api/');