javascript - Node.js 中的 ES6 风格子进程

标签 javascript node.js ecmascript-6

我是一名后院开发人员,在许多项目中使用 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/

相关文章:

javascript - 从 Sequelize 中的另一个表中计数

javascript - 在 Node.js Express 服务器 : res. render(file.ejs, data) 中处理 GET 请求由于未定义数据而无法工作

Javascript div onhover 增量计数

javascript - 模板文字函数传递问题

node.js - Azure 存储移动服务的读取和写入访问策略

javascript - 在 Chrome 中使用 React Native 调试 ES6 import 语句

javascript - jquery中如何完成加载一个函数执行另一个函数的条件?

javascript - 检查任何 DOM 元素的附加事件处理程序

javascript - Vue.js 在 v-for 中使用方法

javascript - SailsJS : Where to define db connection to not supported db type (orientdb)? 自定义中间件?