-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
53 lines (46 loc) · 1.35 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
import { parse } from 'node-html-parser'
import metadataRuleSets from './rulesets.js'
const fetchHead = async (url) => {
const read = async (body) =>
new Promise(async (resolve) => {
let head = ''
for await (const chunk of body) {
head += Buffer.from(chunk).toString()
if (head.toString().split('</head>')[1] !== undefined) {
head += `${head.toString().split('</head>')[0]}</head></html>`
resolve(head)
}
}
resolve(head)
})
/*if (!global.fetch) {
global.fetch = await import('node-fetch')
}*/
const res = await fetch(url)
return read(res.body)
}
const makeUrlAbsolute = (url, path) =>
new URL(path, new URL(url).origin).toString()
export default async function fetchMeta(url) {
const head = await fetchHead(url)
const dom = parse(head)
const metadata = {
url,
}
for (const prop in metadataRuleSets) {
for (const rule of metadataRuleSets[prop].rules) {
const el = dom.querySelector(rule[0])
if (el) {
let data = rule[1](el)
metadata[prop] = metadataRuleSets[prop].absolute
? makeUrlAbsolute(url, data)
: data
break
}
}
if (!metadata[prop] && metadataRuleSets[prop].defaultValue) {
metadata[prop] = makeUrlAbsolute(url, metadataRuleSets[prop].defaultValue)
}
}
return metadata
}