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

218
Views
How to communicate with external CLIs with nodejs

When interacting with clis, for example, taking npm init, we can run the command and get the output by the following code

const { exec } = require('child_process');
exec('npm init', (err, stdout, stderr) => {
  if (err) {
    console.error(err)
  } else {
   console.log(`stdout: ${stdout}`);
   console.log(`stderr: ${stderr}`);
  }
});

But we cannot pass the project name, version name etc.. How to achieve this. Pls answer with the example of npm init command

Thanks in advance :)

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

0

Use the stdin channel each process provides. For that, use the node child_process.spawn method instead:

const { spawn } = require('child_process');


const npm = spawn('npm', ["init"]);

npm.stdout.pipe(process.stdout);
npm.stderr.pipe(process.stderr);

npm.on("exit", () => {

    console.log("npm exited");
    process.exit();

});


const answers = [
    "my-awesome-cli",        // package name
    "0.0.1",                 // version number
    "desciprtion",           // description
    "index.js",              // entry point
    "",                      // test command
    "",                      // git reposiroty
    "",                      // keywords
    "Marc Stirner",          // author
    "MIT"                    // license
];


setInterval(() => {
    if (answers.length > 0) {

        // get first item from array
        let answer = answers.shift();

        // print value we pass to npm
        console.log("Write to npm child:", answer);

        // write chunk to stdin
        npm.stdin.write(`${answer}\r\n`);

    } else {

        //npm.stdin.end();
        console.log("Hit final enter")
        npm.stdin.write(`\r\n`);

    }
}, 800);

My example spwans the npm command, use the stdin channel to write the answer to the process, and pipe the stdout&stderr output from the npm command to the node.js process.

You can do this with exec too, since it returns as well a child_process object.

Read more on the node.js docs, they are very well documented.

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!