Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

invoke a child process via fork() when using ts-node

I have a typescript project and rather than using tsc first, I'm just running via ts-node directly.

In my code I need to create a child process with fork().

If I run code like child_process.fork('ChildProcess.ts') and ChildProcess.ts contains some typescript only constructs (eg: import {}, export, ...), then the interpreter being node, not ts-node, will fail.

It may be recommended to use something like child_process.exec('node ./node_modules/.bin/ts-node ChildProcess.ts), but I really want/need the IPC communication channel that gets set up between the parent and child processes when fork() specifically is used.

Any ideas on how to achieve this?

Thanks!

like image 747
lostdorje Avatar asked Sep 29 '18 14:09

lostdorje


2 Answers

As the reference states, execArgv in forked process is inherited from current process:

execArgv List of string arguments passed to the executable. Default: process.execArgv.

When entry point runs as:

ts-node index.ts

execArgv defaults to ts-node binary:

[ '...\\ts-node\\dist\\_bin.js' ]

And

child_process.fork('ChildProcess.ts') 

runs with ts-node too.

like image 167
Estus Flask Avatar answered Nov 15 '22 03:11

Estus Flask


If you omit the file extension when forking the process, it works with ts-node during developement, as well as with tsc and node in production.

In your app.ts file:

import { fork } from 'child_process';

fork('./longRunningProcess');

Then you can have TypeScript constructs in your longRunningProcess.ts file. After transpilation to app.js and longRunningProcess.js, it will still work when running with regular node.

like image 25
Konstantin H. Avatar answered Nov 15 '22 04:11

Konstantin H.