Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

217
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda