-
Notifications
You must be signed in to change notification settings - Fork 6
/
Worker.js
35 lines (33 loc) · 1.09 KB
/
Worker.js
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
'use strict';
const {Worker, isMainThread, workerData, parentPort} = require('worker_threads');
require('./Formio');
if (isMainThread) {
module.exports = (task, data) => {
return new Promise((resolve, reject) => {
try {
const worker = new Worker(__filename, {workerData: JSON.parse(JSON.stringify({
task,
data
}))});
worker.on('message', (output) => {
worker.terminate();
return resolve(output);
});
worker.on('error', reject);
worker.on('exit', (code) => {
if (code !== 0) {
reject(new Error(`Worker stopped with exit code ${code}`));
}
});
}
catch (err) {
reject(err);
}
});
};
}
else {
require(workerData.task)(workerData.data).then((output) => {
parentPort.postMessage((typeof output === 'string') ? output : JSON.parse(JSON.stringify(output)));
});
}