如何从另一个文件触发子进程代码?

时间:2018-10-24 01:41:37

标签: javascript node.js child-process

我在一个文件index.js中基本上具有这样的代码:

module.exports = {
    const processHandler = require("myOtherFile.js");
    cp = require("child_process");
    cp.fork(pathOfCodeForFork);
    cp.send("message");
}

在另一个文件(myOtherFile.js)中,我有:

process.on("message", function(msg) {
    console.log("here is the message " + msg);
}

文件已加载,但process.on块中的代码从未执行。真的很感谢一些指导。子进程的新手,可能无法正确设置。

1 个答案:

答案 0 :(得分:0)

所以我问了这个问题,但我想出了这个问题,并想发给其他对此感到困惑的人(并要求跟进)。事实证明,从模块中取出对myOtherFile.js的需求会使它正常工作(因此,将const processHandler = require(“ myOtherFile.js”);放在模块代码上方)。后续行动,我不确定为什么吗?模块内部和外部对过程的引用是否不同?还是这通函需要某种方式发出?这与事情的执行顺序有关吗?还有吗?