Skip to content

Instantly share code, notes, and snippets.

@bellbind
Created June 29, 2018 06:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save bellbind/7b412e07a746ea42b9cfa840fd535557 to your computer and use it in GitHub Desktop.
Save bellbind/7b412e07a746ea42b9cfa840fd535557 to your computer and use it in GitHub Desktop.
[nodejs][worker_threads] async req/res to Worker with MessageChannel
// 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;
}
// 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: []});
});
@bellbind
Copy link
Author

worker_threads: node.js >= 10.5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment