Skip to content

Instantly share code, notes, and snippets.

@dylanbr
Created July 17, 2019 08:47
Show Gist options
  • Save dylanbr/3ecf396055d6a425a9160a8ec37ccc79 to your computer and use it in GitHub Desktop.
Save dylanbr/3ecf396055d6a425a9160a8ec37ccc79 to your computer and use it in GitHub Desktop.
Node 12 worker threads
// To run: node --no-warnings --experimental-modules index.js
import {
Worker,
isMainThread,
parentPort,
workerData,
} from 'worker_threads';
import { basename } from 'path';
import { fileURLToPath } from 'url';
const scriptFilename = basename(fileURLToPath(import.meta.url));
if (isMainThread) {
const worker = new Worker(`./${scriptFilename}`, {
workerData: 'Hello!',
});
worker.on('message', (data) => {
console.log('parent:', data);
});
worker.on('online', () => {
console.log('parent: Child spotted.');
});
worker.on('exit', () => {
console.log('parent: Farewell.');
});
} else {
console.log('child:', workerData);
parentPort.postMessage('And hello to you!');
console.log('child: Good bye.');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment