-
Notifications
You must be signed in to change notification settings - Fork 0
/
loopHttpFile.js
93 lines (85 loc) · 2.14 KB
/
loopHttpFile.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
var url = require('url');
var http = require('http');
var host = 'http://lib.sinaapp.com';
var fs = require('fs');
//读取url内容返回值
function read(urls, callback) {
var urlData = url.parse(urls);
var opt = {
host: urlData.hostname,
port: '80',
method: 'GET',
path: urlData.pathname
}
// console.log(opt.host,opt.path);
var body = '';
// var req = http.request(opt, function(res) {
var req = http.request(urls, function(res) {
res.on('data', function(d) {
body += d;
}).on('end', function() {
// console.log(res.headers);
callback(body)
});
}).on('error', function(e) {
body = e.message;
callback(body)
})
req.end();
}
function getAHref(htmlstr) {
var reg = /<a.+?href=('|")?([^'"]+)('|")?(?:\s+|>)/gim;
var arr = [];
while (tem = reg.exec(htmlstr)) {
tem[2].indexOf('http') < 0 && arr.push(tem[2]);
}
return arr;
}
function loopCreatFile(url) {
read(url, function(data) {
var hrefArr = getAHref(data);
hrefArr.forEach(function(item) {
if (item.indexOf('/?') > -1) {
var pathArr = item.split('path=');
var dirObj = getFileDir(pathArr[1]);
fs.exists(dirObj.fullDir + '/' + dirObj.curDir, function(exists) {
if (!exists) {
fs.mkdirSync(dirObj.fullDir + '/' + dirObj.curDir)
}
})
loopCreatFile(host + item)
} else {
if (item.indexOf('?path=') < 0) {
var pathArr = item.split('/js/');
var dirObj = getFileDir(pathArr[1])
console.log(dirObj.fullDir, dirObj.curDir)
read(host + item, function(data) {
try {
fs.writeFileSync(dirObj.fullDir + '/' + dirObj.curDir, data)
} catch (e) {
console.log(e);
}
})
}
}
})
})
}
function getFileDir(str) {
var obj = {}
var dirArr = str.split('/');
obj.curDir = dirArr.pop();
obj.fullDir = dirArr.join('/') == '' ? 'lib/' : 'lib/' + dirArr.join('/');
// console.log(dirArr,obj.fullDir)
return obj;
}
loopCreatFile('http://lib.sinaapp.com')
// read('http://lib.sinaapp.com', function(data) {
// var hrefListArr = getAHref(data);
// console.log(hrefListArr);
// // fs.exists(,function(exists){
// // if(!exists){
// // fs.mkdirSync()
// // }
// // })
// })