-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLegacyNodeWorker.ts
68 lines (57 loc) · 1.51 KB
/
LegacyNodeWorker.ts
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*!
* @author electricessence / https://github.com/electricessence/
* @license MIT
* Based upon Parallel.js: https://github.com/adambom/parallel.js/blob/master/lib/Worker.js
*/
import {Action} from '@tsdotnet/common-interfaces';
import ObservableBase from '@tsdotnet/observable-base/dist/ObservableBase';
import {WorkerLike} from './WorkerLike';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const ps = require('child_process');
//import {ChildProcess} from "child_process";
/**
* This class takes the place of a WebWorker
*/
export default class LegacyNodeWorker
extends ObservableBase<any>
implements WorkerLike
{
onmessage?: Action<{ data: any }> | null;
onerror?: Action<any> | null;
private _process: any;
constructor (url: string)
{
super();
const process = this._process = ps.fork(url);
process.on('message', (msg: string) => this._onNext(JSON.parse(msg)));
process.on('error', (err: any) => this._onError(err));
}
postMessage (obj: unknown): void
{
this.throwIfDisposed();
this._process.send(JSON.stringify({data: obj}));
}
terminate (): void
{
this.dispose();
}
protected _onNext (data: unknown): void
{
super._onNext(data);
if(this.onmessage)
this.onmessage({data: data});
}
protected _onError (error: unknown): void
{
super._onError(error);
if(this.onerror)
this.onerror(error);
}
protected _onDispose (): void
{
super._onDispose();
this._process.removeAllListeners(); // just to satisfy paranoia.
this._process.kill();
this._process = null;
}
}