繁体   English   中英

Node.js 中的 ES6 风格子进程

[英]ES6 style child process in Node.js

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

编辑:

我也在 n Node.js help git tracker 上问过这个问题,并指出了这个问题。 send() 发生在 IPC 连接建立之前。 将 Kid.send() 放入 setTimeout 证明了这一点。 正如有人向我指出的那样,在没有确认连接的情况下,不应尝试任何消息交换。

安装 babel

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' }

您还可以使用“createRequire”,它非常简单(使用 NodeJs 14.15.5 测试):

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

并在您的代码中:

shellExec.exec(command,callback);

您还可以使用 shellExec 中的其他方法,如 ChilldProcess 、 execFile、 execFileSync、 Fork、 spawn、 spawnSync

我经常将这种技术用于不支持“导入”的“旧模块”,例如 MongoDb。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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