register icon indicating copy to clipboard operation
register copied to clipboard

swc-node doesn't work if child_process.fork is used in .ts

Open niyarlatotep opened this issue 3 years ago • 9 comments

Hello! When I try to run my typescript file which contains child_process.fork using swc-node I get the following error:

//main.ts
child_process.fork(__dirname + '/testsRunner/testsRunner.js', args, {cwd: process.cwd()})

internal/modules/cjs/loader.js:1023
  throw err;
  ^

Error: Cannot find module 'C:\src\testsRunner\testsRunner.js'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:1020:15)
    at Function.Module._load (internal/modules/cjs/loader.js:890:27)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}

It is because .js file doesn't really exist it supposed to be compiled on the fly. There is only testsRunner.ts file. Is there a way to get it working?

niyarlatotep avatar Sep 17 '20 18:09 niyarlatotep

You should create a js file which imports @swc/register and then testRunner.ts

kdy1 avatar Sep 18 '20 00:09 kdy1

@kdy1 Thank you for quick responce! Is there a way to make it without .js file?

niyarlatotep avatar Sep 18 '20 05:09 niyarlatotep

You can use -r option of node itself to load @swc/register like node -r @swc/register path/to/your/file.ts, but I'm not sure if fork() supports it. If it doen't support it, you can use spawn() instead

kdy1 avatar Sep 18 '20 05:09 kdy1

@kdy1 Unfortunately it doesn't work will try to use spawn thanks.

niyarlatotep avatar Sep 18 '20 06:09 niyarlatotep

@kdy1 Worker threads are also unsupported. Is there any plans to support these features fork and threads? Is it ever possible in swc-node?

niyarlatotep avatar Sep 18 '20 06:09 niyarlatotep

@niyarlatotep I want to support it, but I'm not sure if it is possible. Note that swc uses all cpu cores if you use async api and it does not block javascript thread. Almost all computations are done in the other threads.

kdy1 avatar Sep 18 '20 06:09 kdy1

@kdy1 I understand, I use threads and forks for other purposes not connected with swc itself. I just wanted to use swc instead of ts-node (which I see also doesn't support forks and therads) as much more faster alternative. In any case thank you for such a great work!

niyarlatotep avatar Sep 18 '20 07:09 niyarlatotep

As long as your child process calls do not override env variables, setting NODE_OPTIONS=-r @swc/register should suffice. Having this library automatically augment process.env.NODE_OPTIONS at runtime might cause issues with other libraries using child processes.

kherock avatar Feb 11 '21 20:02 kherock

@kherock thank you! I'll try it.

niyarlatotep avatar Feb 12 '21 06:02 niyarlatotep