我是一名后院开发人员,在许多项目中使用 Node.js。我还尝试尽可能使用 ES6 类,因为我更喜欢强加结构的方式。但是,我在让子进程与 ES6 类一起运行时遇到问题。
用于测试,test1.js,一个传统模块:
var cp = require( 'child_process' );
var kid = cp.fork( 'test2.js' );
kid.send( {msg: "Hey there kid"} );
setTimeout( () => { process.exit(0) }, 2000 );
和 test2.js
console.log( "Regular child is alive now" );
function yay( message ) { console.log( "Regular kid got", message ); }
process.on( 'message', (m) => { yay(m) } );
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 );
和 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) } );
执行这些操作后,只有传统子进程会收到消息。实验记录了它的实例化,但没有收到消息。
我做错了什么?或者 ES6 模块是否超出了 Node.js 的范围(使用 --experimental-modules 标志)?
编辑:
我也在 Node.js help git tracker 上问过这个问题,并指出了这个问题。 send() 发生在 IPC 连接建立之前。将 Kid.send() 放入 setTimeout 中就证明了这一点。正如有人向我指出的那样,在没有确认连接的情况下不应尝试进行消息交换。
最佳答案
安装巴贝尔
npm install babel-register babel-preset-es2015 --save-dev
创建调用test1.js
的入口点index.js
文件
require('babel-register')({ presets: [ 'es2015' ] });
require('./test1.js');
现在尝试node index.js
➜ node index.js
Experimental child is alive now
Experimental kid got { msg: 'Hey there kid' }
关于javascript - Node.js 中的 ES6 风格子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51296504/