Is there any simple way to pass a function between processes running through child_process.fork?

  • No, no, of course - Alexey Ten
  • Well, from something there is, in principle, there is - pnp2000
  • This is another function. She has a different context and everything else - Alexey Ten
  • The function is the same, no one spoke about the context, because it is impossible to transfer it in principle, at least without touching the V8 code, I am familiar with the V8 device and I understand that due to the fact that the V8 isolates the js code in the sandbox, it is impossible pull in the current context even through C / C ++ - pnp2000

1 answer 1

Figured out how to do this. Master Node

const nos = require("child_process").fork("./worker.js"); function hello_world() { "use strict"; var str1 = "Hello"; var str2 = "World"; function add_word(s1, s2) { var ret = s1 + " " + s2; return ret; } return add_word(str1, str2); } nos.send({function: hello_world.toString()}); 

Slave node

 process.on("message", function (msg) { "use strict"; var fn = new Function(msg.function.toString().match(/\{([\s\S]*)\}/gi)); console.log("message:" + fn()); });