NodeJS — Fork Child Process with function string instead of file

╄→гoц情女王★ 提交于 2020-01-05 03:45:01

问题


I've looked at the documentation for the fork method, and it only describes providing a file path to the child module file.

Does anyone know if it is possible (and undocumented) to pass in the child module directly instead of via a file? Point being, I would like to dynamically generate the module, then create a child process with it.


回答1:


This would not be possible -- fork() creates a completely different process that do not share context or variables with its parent process.

One option you have would be to generate the module inside the forked process, and passing it the necessary arguments via the command line or via a temporary file so that your child can run:

const data = 'something;
var childProcess = child_process.fork(__dirname + '/worker', [something]);

You can then access the arguments from the child using process.argv[2].

One limitation of that approach is that you can only pass data types, and cannot call from the worker any function in the context of its parent. You would need for that some kind of RPC between the child and the parent, which is beyond the scope of this answer.



来源:https://stackoverflow.com/questions/55048262/nodejs-fork-child-process-with-function-string-instead-of-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!