-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcategory_gen.js
More file actions
70 lines (62 loc) · 1.77 KB
/
category_gen.js
File metadata and controls
70 lines (62 loc) · 1.77 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
var http = require('http');
var fs = require('fs');
var cheerio = require('cheerio');
var options = {
host: 'moodle.insa-toulouse.fr',
path: '/'
};
var callbackCategory = function(response) {
var str = '';
var category = [];
var extractCoursesNum = function (num) {
if (num.length) {
return parseInt(num.substr(2,1));
} else {
return 0;
}
};
var walkCategoryDOM = function(node, parentId) {
var nodeInfo = node.children('.info');
var nodeContent = node.children('.content');
var categoryId = node.data('categoryid');
category.push({
_id: categoryId,
name: nodeInfo.find('a').text(),
parent_id: parentId,
courses_num: extractCoursesNum(nodeInfo.find('.numberofcourse').text())
});
console.log('Category ' + categoryId + ' : ' + nodeInfo.find('a').text() + ', parent = ' + parentId);
if (!nodeContent.is(':empty')) {
nodeContent
.children('.subcategories')
.children('.category')
.each(function(k,v) {
var node = $(v);
walkCategoryDOM(node, categoryId);
});
}
};
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
$ = cheerio.load(str);
$('#frontpage-category-names')
.children('.frontpage-category-names')
.children('.content')
.children('.subcategories')
.children('.category')
.each(function (k, v) {
var node = $(v);
walkCategoryDOM(node, 0);
});
var stream = fs.createWriteStream('category.json');
stream.once('open', function(fd) {
for (var i = 0; i < category.length; i++) {
stream.write(JSON.stringify(category[i]) + '\n');
}
stream.end();
});
});
};
http.request(options , callbackCategory).end();