Skip to content

Commit 83ca7ee

Browse files
committed
docs: add thread example
just used as comparison
1 parent 53dc7d9 commit 83ca7ee

File tree

3 files changed

+71
-0
lines changed

3 files changed

+71
-0
lines changed

examples/thread/index.js

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
'use strict'
2+
3+
const path = require('path')
4+
5+
const SCRIPT_PATH = path.resolve(__dirname, 'worker.js')
6+
7+
const { Worker } = require('worker_threads')
8+
9+
const main = async () => {
10+
const url = 'http://vercel.com'
11+
const html = await fetch(url).then(res => res.text())
12+
13+
const worker = new Worker(SCRIPT_PATH, {
14+
workerData: {
15+
url,
16+
html
17+
}
18+
})
19+
20+
const { promise, resolve, reject } = Promise.withResolvers()
21+
22+
worker.on('message', resolve)
23+
worker.on('error', reject)
24+
return promise
25+
}
26+
27+
main()
28+
.then(result => {
29+
console.log(JSON.parse(result))
30+
})
31+
.catch(error => {
32+
console.error(error)
33+
process.exit(1)
34+
})

examples/thread/package.json

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"name": "@tinyspawn/process-message",
3+
"private": true,
4+
"devDependencies": {
5+
"@mozilla/readability": "latest",
6+
"happy-dom": "latest"
7+
}
8+
}

examples/thread/worker.js

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
'use strict'
2+
3+
const { Readability } = require('@mozilla/readability')
4+
5+
const { workerData, parentPort } = require('node:worker_threads')
6+
7+
const parseReader = reader => {
8+
try {
9+
return reader.parse()
10+
} catch (_) {
11+
return {}
12+
}
13+
}
14+
15+
const getDocument = ({ url, html }) => {
16+
const { Window } = require('happy-dom')
17+
const window = new Window({ url })
18+
const document = window.document
19+
document.documentElement.innerHTML = html
20+
return document
21+
}
22+
23+
const main = async ({ url, html, readabilityOpts } = {}) => {
24+
const document = getDocument({ url, html })
25+
const reader = new Readability(document, readabilityOpts)
26+
return parseReader(reader)
27+
}
28+
29+
main(workerData).then(result => parentPort.postMessage(JSON.stringify(result)))

0 commit comments

Comments
 (0)