-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
40 lines (33 loc) · 1.3 KB
/
index.js
File metadata and controls
40 lines (33 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import express from 'express';
import { Worker, isMainThread, parentPort, workerData } from 'worker_threads';
import { fileURLToPath } from 'url';
const app = express();
const PORT = process.env.PORT || 3000;
const __filename = fileURLToPath(import.meta.url);
app.get('/blocking', (req, res) => {
// Simulate a blocking operation
if(isMainThread) {
let worker = new Worker(new URL('./worker.js', import.meta.url), { workerData: 'passed from parent' });
worker.on('message', (message) => {
console.log('Message from worker:', message);
res.status(200).send(message);
});
worker.on('error', (error) => {
console.error('Worker error:', error);
res.status(500).send('Worker error');
});
worker.on('exit', (code) => {
if (code !== 0)
console.error(`Worker stopped with exit code ${code}`);
res.status(500).send('Worker stopped with exit code');
});
// Messages sent from the parent thread using worker.postMessage() are available in worker using parentPort.on('message')
worker.postMessage('Hello from main thread');
}
});
app.get('/non-blocking', (req, res) => {
res.status(200).send('Non-blocking operation started');
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});