Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

68
Views
Write to stdin of spawned child_process while it can be separately stopped

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The simplified example is actually working fine. Something must be up with my original code.

Output:

-> % node sample.js
child: from parent: ping
child: pong
child: from parent: ping
child: pong
^C
parent: stop requested
child: from parent: stop
child: from parent: ping
parent: stopping on our own discretion
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!