0

There is a package which is a command line utility script. It uses the prompts library to display questions and then performs actions based on the answers.

I want to run this script programmatically. I can see that the prompts library exposes an overrides method to let answers be set programmatically, but I do not have access to the source of the script to add this functionality in. Also, the script does not export any functions so it cannot be wrapped in another script.

How can run the script in a way that lets me set prompts.override() ?

Dan
  • 3,229
  • 2
  • 21
  • 34
  • doc exemple for override use it in combination with cli program arguments, maybe your cli original dev have also used it in that way ? https://github.com/terkelg/prompts/blob/master/readme.md#override – r043v Aug 05 '22 at 10:12
  • 2
    If you know the order of the questions and the answers you want to give, you can use `child_Process.exec` and provide the stdin to that child process from your wrapper script like shown in this question https://stackoverflow.com/questions/37685461/how-to-pass-stdin-to-node-js-child-process – derpirscher Aug 08 '22 at 15:55
  • "_There is a package which is_...": This is very mysterious. Show us (and link us to) the actual code! – jsejcksn Aug 08 '22 at 18:11
  • @jsejcksn the code is internal – Dan Aug 09 '22 at 11:20
  • 1
    @Dan Can you be more explicit? Can you provide an example of what tou want to achieve? – Alaindeseine Aug 15 '22 at 09:03

1 Answers1

1

Example code:

const prompts = require('prompts');
prompts.override(require('yargs').argv);

(async () => {
  const response = await prompts([
    {
      type: 'text',
      name: 'twitter',
      message: `What's your twitter handle?`
    },
    {
      type: 'multiselect',
      name: 'color',
      message: 'Pick colors',
      choices: [
        { title: 'Red', value: '#ff0000' },
        { title: 'Green', value: '#00ff00' },
        { title: 'Blue', value: '#0000ff' }
      ],
    }
  ]);

  console.log(response);
})();

How @emersonthis managed to add stdin to the child_process:

var cp = require('child_process');
var optipng = require('pandoc-bin').path; //This is a path to a command
var child = cp.spawn(optipng, ['--from=markdown', '--to=html']); //the array is the arguments

child.stdin.write('# HELLO'); //my command takes a markdown string...

child.stdout.on('data', function (data) {
    console.log('stdout: ' + data);
});
child.stdin.end();

You can implement something similar to this, but you have to know the order you want your answers and questions to appear as.

Relevant sources:

DialFrost
  • 1,610
  • 1
  • 8
  • 28