Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

216
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda