Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Node non blocking using workers
const express = require('express');
const { Worker } = require('worker_threads');
const app = express();
app.get('/', function (req, res) {
const worker = new Worker(__dirname + '/worker.js', {
workerData: { ping: 'pong' },
});
worker.on('message', (pi) => {
res.send(`Pi Value, ${pi}`);
});
worker.on('error', (err) => {
res.status({ status: 500 }).json({ message: err.message });
});
worker.on('exit', (code) => {
if (code !== 0) {
res.status({ status: 500 }).json({ message: code });
}
});
worker.postMessage('getMeThePiValue');
});
app.get('/hello', function (req, res) {
res.send(`hello world`);
});
app.listen(3000);
const { parentPort, workerData } = require('worker_threads');
function getPi() {
let sum = 0;
for (let n = 0; n < 10000000000; n++) {
let mult = n % 2 === 0 ? 1 : -1;
sum += mult * (1 / (2 * n + 1));
}
return sum * 4;
}
parentPort.on('message', (param) => {
console.log(param); // getMeThePiValue
console.log(workerData); // { ping: 'pong'}
const pi = getPi();
parentPort.postMessage(pi);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment