-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
136 lines (121 loc) · 2.59 KB
/
index.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
'use strict';
var fs = require('fs');
var extend = require('extend');
var jade = require('jade');
var path = require('path');
var cheerio = require('cheerio');
function getFiles(options) {
options = extend({
path: './',
extension: '.html',
name: 'result',
title: 'project-map'
}, options);
walker(options.path, options.extension, function(error, result) {
if (error) {
throw error;
}
var data = {
title: options.title,
list: []
};
var len = result.length;
Promise.prototype.thenReturn = function(value) {
return this.then(function() {
return value;
});
};
function readFile(filePath) {
return new Promise(function(resolve) {
getTitle(filePath, options.path, function(title) {
data.list.push(title);
resolve();
});
});
}
Promise.resolve(0).then(function loop(i) {
if (i < len) {
return readFile(result[i])
.thenReturn(i + 1)
.then(loop);
}
}).then(function() {
writeResultFile(options, data);
console.log('done');
}).catch(function(error) {
console.log('error', error);
});
});
}
/**
* Write result file
* @param options
* @param data
*/
function writeResultFile(options, data) {
jade.renderFile(__dirname + '/result.jade', {pretty: true, data: data}, function(error, html) {
if (error) {
console.log('error:\n' + error);
}
fs.writeFile(options.path + '/' + options.name + '.html', html, function(err) {
if (err) {
return console.log(err);
}
});
});
}
function walker(directory, extension, callback) {
var results = [];
fs.readdir(directory, function(error, list) {
if (error) {
return callback(error);
}
var i = 0;
(function next() {
var file = list[i];
i += 1;
if (!file) {
return callback(null, results);
}
file = directory + '/' + file;
fs.stat(file, function(error, stat) {
if (stat && stat.isDirectory()) {
walker(file, extension, function(error, res) {
results = results.concat(res);
next();
});
} else {
if (path.extname(file) === extension) {
results.push(file);
}
next();
}
});
})();
});
}
/**
*
* @param url
* @param removePath
* @param callback
*/
function getTitle(url, removePath, callback) {
callback = callback ? callback : function() {
};
fs.readFile(url, 'utf8', function(error, data) {
url = url.replace(removePath + '/', '');
var _fileInfo = {
title: url,
link: url
};
if (error) {
callback(_fileInfo);
}
var $ = cheerio.load(data);
var _title = $('title');
_fileInfo.title = _title.text() || url;
callback(_fileInfo);
});
}
module.exports = getFiles;