Created
June 29, 2018 06:22
-
-
Save bellbind/7b412e07a746ea42b9cfa840fd535557 to your computer and use it in GitHub Desktop.
[nodejs][worker_threads] async req/res to Worker with MessageChannel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// node.js worker_threads module example: main thread side | |
//$ node --exprimental-worker main.js | |
const path = require("path"); | |
const {Worker, MessageChannel} = require("worker_threads"); | |
//NOTE: worker code accepts only absolute file path | |
// not URLs includes "data:" URL | |
const w = new Worker(path.resolve(__dirname, "./worker.js")); | |
(async () => { | |
console.log(await send(w, "Hello")); | |
console.log(await send(w, "World")); | |
w.terminate(); | |
})().catch(console.error); | |
// req/res style communication to workers | |
async function send(worker, data) { | |
const mc = new MessageChannel(); | |
const res = new Promise(resolve => { | |
mc.port1.once("message", ({data}) => resolve(data)); | |
}); | |
// Worker and Port uses node.js EventEmitter, not DOM EventTarget | |
// No event class, post any objects to serializable | |
// passing ports explicitly on the first argument: | |
// It should also set second ports args | |
const ports = [mc.port2]; | |
worker.postMessage({data, ports}, ports); | |
return await res; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// node.js worker_threads example: worker side code | |
// NOTE: in main, parentPort is null | |
const {parentPort} = require("worker_threads"); | |
// As DOM MessageEvent style parameters | |
parentPort.on("message", ({data, ports}) => { | |
// echo response also as a MessageEvent like | |
ports[0].postMessage({data, ports: []}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
worker_threads: node.js >= 10.5