gpt4 book ai didi

javascript - Node.JS fork 管道

转载 作者:搜寻专家 更新时间:2023-10-31 22:59:36 24 4
gpt4 key购买 nike

我正在尝试按照 this stackoverflow question 上发布的示例将 node.js 模块作为子进程进行 fork 。 fork 本身可以工作,但我遇到的问题是 Node 试图在 .on('data').on('exit') 之前添加fork('./DaemonSerial.js' 填充 tChild

var fork = require('child_process').fork;

// Start Serial Daemon/s
var tChild = fork('./DaemonSerial.js', [], {
stdio: 'pipe'
});
tChild.stdin.on('data', function(data) {
// output from the child process
console.log("./DaemonSerial.js >>> " + data)
});
EdgeMaster.Children[tChild.pid] = tChild;
tChild.on('exit', function(d) {
console.log("./DaemonSerial.js >>> "+ tChild.pid + ' Exited:'+ d);
delete EdgeMaster.Children[tChild.pid]
});

我在其他地方也遇到过这个问题,并且我有理由相信应该有一种方法可以强制执行 do THIS then THAT 类型的功能,即使函数本身没有回调。 nodejs.org/api/child_process.html 上的 child_process.fork(modulePath, [args], [options]) 没有列出回调。

想法?

编辑: 我编写了一个新脚本 forktest.js 以排除我脚本的其他部分可能导致问题的任何可能性。 forktest.js具体如下:

var fork = require('child_process').fork;

var ForkDict = {};

function forkit(aPath){
tChild = fork( aPath, [], {stdio: 'pipe'});
ForkDict[tChild.pid] = tChild;
ForkDict[tChild.pid].path = aPath;
tChild.stdout.on('data', function(data) {
// output from the child process
console.log( this.path +'>>> '+ data);
}.bind(this));
tChild.on('exit', function(d) {
console.log( this.path +'>>> Exited:'+ d);
delete ForkDict[tChild.pid]
}.bind(this));
}

forkit('./DaemonSerial.js');

控制台的错误如下:

pi@raspberrypi ~ $ node forktest.js

/home/pi/forktest.js:9
tChild.stdout.on('data', function(data) {
^
TypeError: Cannot call method 'on' of null
at forkit (/home/pi/forktest.js:9:19)
at Object.<anonymous> (/home/pi/forktest.js:19:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:901:3

最佳答案

fork 是异步的,但它的返回值不是异步填充的。它返回一个继承自 EventEmitter 的 ChildProcess 实例。 EventEmitter 通常用于异步任务,但您可以在发生某些事情时接收事件,而不是使用回调。就像它在 docs 中所说的那样:

These methods follow the common async programming patterns (accepting a callback or returning an EventEmitter).

在第一个例子中:

  • fork 没有 stdio 选项。您可能应该改用 silent: true;它调用 spawn 并将 stdio 选项设置为“pipe”。
  • 您尝试从可写流 (stdin) 中读取:tChild.stdin.on('data', ... 您可能想使用 stdout

看起来 stdinstdout 可以是 null 取决于你是否使用 silent: true .请参阅 fork 文档中的 options.silent:

Boolean If true, stdin, stdout, and stderr of the child will be piped to the parent, otherwise they will be inherited from the parent, see the "pipe" and "inherit" options for spawn()'s stdio for more details (default is false)

所以数据只是进入你的主脚本的stdout。您可以通过以下方式解决此问题(请注意您的 stdio 选项没有执行任何操作):

tChild = fork( aPath, [], {silent: true});

正如我之前所说,您需要在 stdout 上监听 data 事件。

关于javascript - Node.JS fork 管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22275556/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com