GoogleChromeLabs / GoogleChromeLabs/comlink

Making Comlink.proxy() work in node worker threads

Open
#313 3 comments 7 reactions 0 assignees View on GitHub
Dominant language
TypeScript
Stars
12.8k
Forks
435
PR merge metrics
No merged PRs in 30d

Description

Took me a while to figure out how to make `Comlink.proxy()` work in node worker threads. I'm not sure that Comlink itself needs to handle this, since the simple workaround is to override the default `proxy` transfer handler. Here's how I did it for anyone curious

```javascript
// In worker-thread
const { parentPort } = require('worker_threads')
const { MessageChannel } = require('worker_threads')

const Comlink = require('comlink')
const nodeEndpoint = require('comlink/dist/umd/node-adapter.js')

// Override comlink's default proxy handler to use Node endpoints
Comlink.transferHandlers.set('proxy', {
canHandle: obj => obj && obj[Comlink.proxyMarker],
serialize: obj => {
const { port1, port2 } = new MessageChannel()
Comlink.expose(obj, nodeEndpoint(port1))
return [port2, [port2]]
},
deserialize: port => {
port = nodeEndpoint(port)
port.start()
return Comlink.wrap(port)
}
})

const thingToProxy = '...'
const api = {
thingToProxy: Comlink.proxy(thingToProxy)
hello () {
return 'HELLO12341567'
},
}

Comlink.expose(api, nodeEndpoint(parentPort))

```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.