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.
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.