For a CLI parent process, I have a child process that I need to write some data to before it is stopped (e.g. WebSocket close code other than 1006).
This snippet represents what I'm doing:
setInterval(() => child.stdin.write("ping\n"), 1000);
const { spawn } = require("child_process");
const child = spawn("node", ["-e", `
setInterval(() => console.log("child: pong"), 1000);
process.on("beforeExit", () => {
console.log("child: stopping");
});
process.stdin.on("close", () => console.log("stdin close"));
process.stdin.on("finish", () => console.log("stdin finish"));
process.on("SIGINT", () => console.log("child: SIGINT"));
process.stdin.on("data", (c) => console.log("child: from parent:", c.toString("utf8").trim()));
`], {
detached: true,
//// if 'ignore' is used, child.stdin is undefined
// stdio: ["ignore", "inherit", "inherit"],
});
child.stdout.pipe(process.stdout);
child.stderr.pipe(process.stderr);
process.on("SIGINT", () => {
console.log("parent: stop requested");
child.stdin.write("stop\n"); // cleanup something
setTimeout(() => {
console.log("parent: stopping on our own discretion");
child.kill(0);
process.exit(0);
}, 500);
});
I've tried to use a Stream.Readable or a Passthrough as stdio stream property, but it seems NodeJS only allows for file descriptor streams to be used. I don't want to go as far as creating a temporary file just for this case.
I feel this should be possible/trivial but I'm pulling my hair out to get it to work.