-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
executable file
·67 lines (55 loc) · 1.62 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
#!/usr/bin/env node
const program = require('commander');
const jsdom = require('jsdom');
const pkg = require('./package.json');
const Readability = require('readability');
const { JSDOM } = jsdom;
const jsdomConsole = new jsdom.VirtualConsole();
// Suppress these errors for now
jsdomConsole.on('jsdomError', () => {});
const options = {
features: {
FetchExternalResources: false,
ProcessExternalresources: false,
},
virtualConsole: jsdomConsole,
};
const readability = (dom) => {
// Happens on missing file
if (!dom) return;
const article = new Readability(dom.window.document).parse();
if (!article) {
console.error('Error: Readability returned nothing. This usually happens on empty input');
return;
}
console.log('<h1>', article.title, '</h1>', article.content);
};
const isURL = (str) => {
const regex = new RegExp('^https?:\\/\\/');
return regex.test(str);
};
const handleError = err => console.error(err.toString());
const run = (sources) => {
const promises = sources.map(source =>
(isURL(source) ?
JSDOM.fromURL(source, options) :
JSDOM.fromFile(source, options)
));
Promise.all(promises).then((doms) => {
doms.forEach(readability);
})
.catch(handleError);
};
program
.version(pkg.version)
.arguments('[sources...]')
.description('Parses each source with Readability and prints cleaned HTML to stdout. source can be a file path or URL.')
.action(run)
.parse(process.argv);
if (program.args.length === 0) {
if (!process.stdin.isTTY) {
JSDOM.fromFile('/dev/stdin', options).then(readability).catch(handleError);
} else {
program.outputHelp();
}
}