Skip to content

Commit 53dc7d9

Browse files
committed
docs: add ipc example
1 parent d3c501a commit 53dc7d9

File tree

3 files changed

+65
-0
lines changed

3 files changed

+65
-0
lines changed

examples/ipc/index.js

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
'use strict'
2+
3+
const path = require('path')
4+
const $ = require('../../src')
5+
6+
const SCRIPT_PATH = path.resolve(__dirname, 'worker.js')
7+
8+
const main = async () => {
9+
const subprocess = $('node', [SCRIPT_PATH], {
10+
detached: process.platform !== 'win32',
11+
stdio: ['pipe', 'pipe', 'pipe', 'ipc']
12+
})
13+
14+
const url = 'http://vercel.com'
15+
const html = await fetch(url).then(res => res.text())
16+
17+
subprocess.send({ url, html })
18+
19+
const { promise, resolve, reject } = Promise.withResolvers()
20+
21+
subprocess.on('message', resolve)
22+
subprocess.on('error', reject)
23+
return promise
24+
}
25+
26+
main()
27+
.then(result => console.log(result))
28+
.catch(error => {
29+
console.error(error)
30+
process.exit(1)
31+
})

examples/ipc/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/ipc/worker.js

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

0 commit comments

Comments
 (0)