简体   繁体   中英

ES6 style child process in Node.js

I'm a backyard developer, using Node.js for a number of projects. I'm also attempting to use ES6 classes where possible, as I prefer the way structure is imposed. However, I'm having problems getting child processes to function with ES6 classes.

For testing, test1.js, a traditional module:

var cp = require( 'child_process' );
var kid = cp.fork( 'test2.js' );
kid.send( {msg: "Hey there kid"} );
setTimeout( () => { process.exit(0) }, 2000 );

And test2.js

console.log( "Regular child is alive now" );
function yay( message ) { console.log( "Regular kid got", message ); }
process.on( 'message', (m) => { yay(m) } );  

The same in ES6, test1.mjs:

import cp from 'child_process';
const kid = cp.fork( 'test2.mjs' );
kid.send( { msg: "Hey there kid" } );
setTimeout( () => { process.exit(0) }, 2000 );  

And test2.mjs

class Test2 {
  constructor() {
    console.log( "Experimental child is alive now" );
  }
  yay(message) {
    console.log( "Experimental kid got", message );
  }
}
const test2 = new Test2();
process.on( 'message', (m) => { test2.yay(m) } );

Executing these, only the traditional child receives the message. The experimental one logs it's instantiation, but no message received.

What am I doing wrong? Or are ES6 modules well out of scope for Node.js (using --experimental-modules flag)?

EDIT:

I've asked this question on n Node.js help git tracker too, and had the issue pointed out. The send() was occurring before the IPC connection was established. Putting the kid.send() into a setTimeout demonstrated this. As it was pointed out to me, no message exchange should be attempted without a confirmed connection.

Install babel

npm install babel-register babel-preset-es2015 --save-dev

Create entry point index.js file that calls test1.js

require('babel-register')({ presets: [ 'es2015' ] });

require('./test1.js');

Now try node index.js

➜  node index.js 
Experimental child is alive now
Experimental kid got { msg: 'Hey there kid' }

You can also use 'createRequire', it's very simple (Tested with NodeJs 14.15.5) :

import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const shellExec = require('child_process');

and in your code :

shellExec.exec(command,callback);

You can also use other methods from shellExec like ChilldProcess , execFile, execFileSync, Fork, spawn, spawnSync

I often use this technic for "old modules" not supporting "import", like MongoDb.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM