1
1
import { fileURLToPath } from 'node:url' ;
2
- import child_process from 'node:child_process ' ;
2
+ import { Worker , isMainThread , parentPort } from 'node:worker_threads ' ;
3
3
4
4
/**
5
5
* Runs a task in a subprocess so any dangling stuff gets killed upon completion.
@@ -11,23 +11,21 @@ import child_process from 'node:child_process';
11
11
* @returns {(opts: T) => Promise<U> } A function that when called starts the subprocess
12
12
*/
13
13
export function forked ( module , callback ) {
14
- if ( process . env . SVELTEKIT_FORK && process . send ) {
15
- process . send ( { type : 'ready' , module } ) ;
16
-
17
- process . on (
14
+ if ( ! isMainThread && parentPort ) {
15
+ parentPort . on (
18
16
'message' ,
19
17
/** @param {any } data */ async ( data ) => {
20
18
if ( data ?. type === 'args' && data . module === module ) {
21
- if ( process . send ) {
22
- process . send ( {
23
- type : 'result' ,
24
- module,
25
- payload : await callback ( data . payload )
26
- } ) ;
27
- }
19
+ parentPort ?. postMessage ( {
20
+ type : 'result' ,
21
+ module,
22
+ payload : await callback ( data . payload )
23
+ } ) ;
28
24
}
29
25
}
30
26
) ;
27
+
28
+ parentPort . postMessage ( { type : 'ready' , module } ) ;
31
29
}
32
30
33
31
/**
@@ -36,34 +34,31 @@ export function forked(module, callback) {
36
34
*/
37
35
const fn = function ( opts ) {
38
36
return new Promise ( ( fulfil , reject ) => {
39
- const child = child_process . fork ( fileURLToPath ( module ) , {
40
- stdio : 'inherit' ,
37
+ const worker = new Worker ( fileURLToPath ( module ) , {
41
38
env : {
42
- ...process . env ,
43
- SVELTEKIT_FORK : 'true'
44
- } ,
45
- serialization : 'advanced'
39
+ ...process . env
40
+ }
46
41
} ) ;
47
42
48
- child . on (
43
+ worker . on (
49
44
'message' ,
50
45
/** @param {any } data */ ( data ) => {
51
46
if ( data ?. type === 'ready' && data . module === module ) {
52
- child . send ( {
47
+ worker . postMessage ( {
53
48
type : 'args' ,
54
49
module,
55
50
payload : opts
56
51
} ) ;
57
52
}
58
53
59
54
if ( data ?. type === 'result' && data . module === module ) {
60
- child . kill ( ) ;
55
+ worker . terminate ( ) ;
61
56
fulfil ( data . payload ) ;
62
57
}
63
58
}
64
59
) ;
65
60
66
- child . on ( 'exit' , ( code ) => {
61
+ worker . on ( 'exit' , ( code ) => {
67
62
if ( code ) {
68
63
reject ( new Error ( `Failed with code ${ code } ` ) ) ;
69
64
}
0 commit comments