Repository navigation
Expand file tree
/
Copy pathextractor.js
More file actions
78 lines (68 loc) · 2.06 KB
/
Copy pathextractor.js
File metadata and controls
78 lines (68 loc) · 2.06 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
var readability = require('./index');
var Readability = readability.Readability;
var JSDOMParser = readability.JSDOMParser;
function extract(sourceHTML) {
try {
var doc = useJSDom(sourceHTML);
if(!doc) {
return null;
}
var uri = {
spec: 'http://fakehost/test/page.html',
host: 'fakehost',
prePath: 'http://fakehost',
scheme: 'http',
pathBase: 'http://fakehost/test/'
};
var myReader = new Readability(uri, doc);
var readerable = myReader.isProbablyReaderable();
result = myReader.parse();
var content = result.content;
delete result.content;
console.log(result);
return content;
} catch (err) {
console.error(err, 'failed to reformat');
return null;
}
}
function useJSDOMParser(sourceHTML) {
var parser = new JSDOMParser();
var doc = parser.parse(sourceHTML);
if (parser.errorState) {
console.error('Parsing this DOM caused errors:', parser.errorState);
return null;
}
return doc;
}
function removeCommentNodesRecursively(node) {
for (var i = node.childNodes.length - 1; i >= 0; i--) {
var child = node.childNodes[i];
if (child.nodeType === child.COMMENT_NODE) {
node.removeChild(child);
} else if (child.nodeType === child.ELEMENT_NODE) {
removeCommentNodesRecursively(child);
}
}
}
function useJSDom(sourceHTML) {
var jsdom = require('jsdom').jsdom;
var doc = jsdom(sourceHTML, {
features: {
FetchExternalResources: false,
ProcessExternalResources: false
}
});
removeCommentNodesRecursively(doc);
return doc;
}
if (process.argv.length < 3) {
console.log('node extract.js <html file>');
process.exit(-1);
}
var fileName = process.argv[2]
console.log('extracting', fileName);
var fs = require('fs');
var sourceHTML = fs.readFileSync(fileName, 'utf-8');
var simplifiedHTML = extract(sourceHTML);
fs.writeFileSync(fileName + '.readable.html', simplifiedHTML, 'utf-8');