Skip to content

Instantly share code, notes, and snippets.

@jerrylususu
Created July 29, 2023 13:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jerrylususu/6a8817c20cebc70f922b8a0f034c0c4c to your computer and use it in GitHub Desktop.
Save jerrylususu/6a8817c20cebc70f922b8a0f034c0c4c to your computer and use it in GitHub Desktop.
es module worker
export function fibonacci(num) {
if (num <= 1) return num;
return fibonacci(num - 1) + fibonacci(num - 2);
}
import {Worker, isMainThread, parentPort, workerData} from 'worker_threads';
import { fibonacci as fib } from './fib.js';
console.log('script running');
export function calculateFibonacci(n) {
console.log('isMain', isMainThread);
if (isMainThread) {
return new Promise((resolve, reject) => {
console.log('starting worker');
const worker = new Worker(new URL(import.meta.url).pathname, {
workerData: n,
});
worker.on('message', (value) => {
console.log('worker returned', value);
resolve(value);
});
worker.on('error', reject);
worker.on('exit', (code) => {
console.log(`worker exit, code=${code}`)
if (code !== 0) {
reject(new Error(`Worker stopped with exit code ${code}`));
}
});
});
} else {
}
}
if (!isMainThread) {
console.log('worker inited!');
const result = fib(workerData);
console.log('worker got result', result);
parentPort.postMessage(result);
console.log('worker posted result', result);
process.exit(0);
}
import express from 'express';
import {calculateFibonacci} from './fibworker.js';
const app = express()
const port = 3000
app.get('/fib', async (req, res) => {
console.log('receiving req, start calc');
const fibValue = await calculateFibonacci(42);
res.send(`fib: ${fibValue}\n`)
})
app.get('/', (req, res) => {
console.log('processing hello world start');
res.send(`Hello World!\n`)
console.log('processing hello world end');
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
{
"main": "index.js",
"type": "module",
"scripts": {
"start": "nodemon index.js"
},
"dependencies": {
"express": "^4.18.1"
},
"devDependencies": {
"nodemon": "^2.0.19"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment