-
Notifications
You must be signed in to change notification settings - Fork 1
/
cli.js
executable file
·105 lines (84 loc) · 2.6 KB
/
cli.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
#!/usr/bin/env node
let opsh = require('opsh');
let hred = require('./index.js');
let pkg = require('./package.json');
let fs = require('fs');
let { stdin, stdout } = process;
// Set of options accepting an argument
let accepts_optarg = new Set(['u', 'url', 'f', 'file']);
// Accumulate options and their arguments on the one hand,
// and operands, on the other
let opts = {};
let operands = [];
opsh(process.argv.slice(2), {
option(option, value) {
opts[option] = value !== undefined ? value : true;
},
operand(operand, opt) {
if (opt !== undefined && accepts_optarg.has(opt)) {
opts[opt] = operand;
} else {
operands.push(operand);
}
}
});
if (opts.version || opts.V) {
console.log(pkg.version);
process.exit(0);
}
if (opts.help || opts.h) {
console.log(
`hred version ${pkg.version}
Reduce HTML (and XML) to JSON from the command line.
Details at: https://github.com/danburzo/hred
Usage: hred [options...]
General options:
-h, --help Print this help message
-V, --version Print hred version
Input options:
-u <url>, --url=<url> Specify base URL for relative HTML attributes
-x, --xml Parse input as XML rather than HTML
-f <file>, --file=<file> Read the query from an external file instead of
passing it as an operand.
Output options:
-c, --concat Output array as concatenated JSON records
-r, --raw Output raw (unquoted) strings
Examples:
Get the "alt" and "src" HTML attributes of images on a Wikipedia page:
curl https://en.wikipedia.org/wiki/Banana | hred "img { @alt, @src }"
Read the titles and definitions of HTTP response codes from a MDN page:
curl https://developer.mozilla.org/en-US/docs/Web/HTTP/Status | hred "
dt {
a {
@href,
^ :scope > code @.textContent >> title
} >> .,
:scope + dd @.textContent
}
"
`);
process.exit(0);
}
let query = opts.f || opts.file ? fs.readFileSync(opts.f || opts.file, 'utf8') : operands[0];
let content = '';
stdin
.setEncoding('utf8')
.on('readable', () => {
let chunk;
while ((chunk = stdin.read()) !== null) {
content += chunk;
}
}).on('end', () => {
let res = hred(content, query || '^', opts.url || opts.u, (opts.x || opts.xml) ? 'application/xml' : 'text/html'), out;
if ((opts.concat || opts.c) && Array.isArray(res)) {
out = res.map(it => {
if ((opts.raw || opts.r) && typeof it === 'string') {
return it;
}
return JSON.stringify(it, null, 2);
}).join('\n');
} else {
out = (opts.raw || opts.r) && typeof res === 'string' ? res : JSON.stringify(res, null, 2);
}
stdout.write(out);
});