-
-
Notifications
You must be signed in to change notification settings - Fork 184
Expand file tree
/
Copy pathindex.js
More file actions
62 lines (52 loc) · 1.65 KB
/
Copy pathindex.js
File metadata and controls
62 lines (52 loc) · 1.65 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
'use strict'
const { memoizeOne, composeRule } = require('@metascraper/helpers')
const { Readability } = require('@mozilla/readability')
const asyncMemoizeOne = require('async-memoize-one')
const { Browser } = require('happy-dom')
const parseReader = reader => {
const parsed = reader.parse()
return parsed || {}
}
const getDocument = ({ url, html }) => {
const browser = new Browser({
settings: {
disableComputedStyleRendering: true,
disableCSSFileLoading: true,
disableIframePageLoading: true,
disableJavaScriptEvaluation: true,
disableJavaScriptFileLoading: true
}
})
const page = browser.newPage()
page.url = url
page.content = html
return {
document: page.mainFrame.document,
teardown: () => browser.close()
}
}
const readability = asyncMemoizeOne(async (url, html, readabilityOpts) => {
const { document, teardown } = getDocument({ url, html })
try {
const reader = new Readability(document, readabilityOpts)
const result = parseReader(reader)
return result
} finally {
await teardown()
}
}, memoizeOne.EqualityFirstArgument)
module.exports = ({ readabilityOpts } = {}) => {
const getReadbility = composeRule(($, url) =>
readability(url, $.html(), readabilityOpts)
)
const rules = {
author: getReadbility({ from: 'byline', to: 'author' }),
description: getReadbility({ from: 'excerpt', to: 'description' }),
lang: getReadbility({ from: 'lang' }),
publisher: getReadbility({ from: 'siteName', to: 'publisher' }),
title: getReadbility({ from: 'title' })
}
rules.pkgName = 'metascraper-readability'
return rules
}
module.exports.readability = readability