This repository was archived by the owner on Aug 2, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathindex.js
More file actions
56 lines (50 loc) · 1.45 KB
/
index.js
File metadata and controls
56 lines (50 loc) · 1.45 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
#!/usr/bin/env node
const fs = require('fs');
const { URL } = require('url');
const axios = require('axios');
const cheerio = require('cheerio');
const argv = require('yargs');
const withinComments = new RegExp(/(\s*<!--\s*)([\s\S]*?)(\s*-->\s*)/gm);
function extractDatablocks(markup) {
const $ = cheerio.load(markup);
const datablocks = $('script[type^="application/ld+json"]');
if (datablocks.length > 0) {
datablocks.each((idx, script_el) => {
//console.log(el.attribs.type);
$(script_el).contents().each((idx, el) => {
console.log(el.data.replace(withinComments, '$2'), "\n");
});
});
} else {
console.info('No datablocks found.');
}
}
argv
.usage('Usage: $0 <url|path>')
.command('$0 <url|path>', 'extract datablock(s) from URL or file path',
() => {},
(argv) => {
try {
const url = new URL(argv.url);
axios
.get(argv.url)
.then((res) => {
// TODO: confirm 200, etc
extractDatablocks(res.data);
})
.catch(console.error);
} catch (err) {
if (err.type === URL.ERR_INVALID_URL) {
// we probably have a file path...let's check
const file = fs.readFileSync(argv.path);
extractDatablocks(file.toString());
}
}
}
)
.help()
.argv;
/**
* TODO: avoid these mime types at all costs
* https://www.w3.org/TR/html5/semantics-scripting.html#javascript-mime-type
**/