So basically my question is what would be a better way to achieve my goal? The code below works fine but looks like it is extremely inefficient and could be achieved in a better way. The code essentially spawns several child processes with a dynamic name and because the eval()
function is in the global scope, the child processes are also available in global scope. I need to have the processes available in a global scope since I want to be able to kill each process individually through use of commands. I hope I have explained everything as clear as needed. If there are any questions, feel free to ask.
Thanks.
processName = "child";
for (let a = 0; a < deviceAmount; a++) {
eval(
`
var ${processName + a} = child_process.spawn("node", ["slave.js", ${a + 1}]);
${processName + a}.stdout.setEncoding("utf8");
${processName + a}.stdout.on("data", function (data) {
process.stdout.write(data);
});
${processName + a}.stderr.setEncoding("utf8");
${processName + a}.stderr.on("data", function (data) {
process.stderr.write("ERROR: " + data);
});
${processName + a}.on("close", function (code) {
process.stdout.write("Exited with code: " + code);
});
`
);
}