Reputation: 11
I have an event in my node.js script which need to be called multiple times that spawns a child process. Not parallel just one child process at the time.
var child = spawn('node', [script, arg1],{cwd: "./", stdio: ["pipe","pipe","pipe","ipc"]})
I need to send messages to that child process. With the first spawned process it works just fine with:
child.stdin.write("my_message")//also tried child.stdin.write("my_message\n")
The listener on the spawned script looks like that:
process.stdin.on("data", async(data)=> {
//dosomething
process.exit();
}
But when the first child process is done and closed and the second child process is spawned the child.stdin.write("my_message")
doesn't reach the child process.
I thought there is a problem with the stdtin channel not closing when the child process exited.
So I tried process.stdin.end();
on the child process and all the following functions on the child.on("close")
and child.on("exit")
events
child.on("close", (data)=>{
console.log("Child process closed")
//child.stdin.end();
//child.stdout.end();
//child.stdin.destroy();
//child.kill("SIGINT");
//child = undefined;
//child.disconnect();
//child.ref(); })
I also tried sending messages trough ipc. But this throws 'ERR_IPC_CHANNEL_CLOSED' when trying to send a message to the second spawned child.
node --version v14.17.5
Upvotes: 0
Views: 855
Reputation: 11
Outsourcing the function that spawns the child processes and the associated listeners in an external module actually worked. Not sure why.
//spawnChild.js
module.exports = function(arg1){
var child = spawn('node', [script, arg1],{cwd: "./", stdio: ["pipe","pipe","pipe","ipc"]})
//plus the unmodified child.stderr, child.stdout... listeners in here
}
Calling the new module in the main script with:
var childProcess = require("./spawnChild.js")(arg1)
Upvotes: 1