Skip to content Skip to sidebar Skip to footer

Get Argument From Pipe But Also Run Prompts?

I'm writing a Node script designed to be executed from Bash terminal. It takes a couple of filenames and then asks questions to the user via a prompt about how to process them. I'm

Solution 1:

I found a solution using a combination of packages, namely prompts and ttys.

I switched to prompts because it allows you to configure a variable called stdin for each question which means you can decide where to take input from.

Most prompt packages seem to default to using process.stdin as the input. This is normally fine but when you pipe data into a command, process.stdin is occupied by the pipe, hence the problem I was having before. However, if you know that process.stdin is occupied by the pipe you can still get keyboard input from the user.

This is where ttys comes in. It's a very simple package which checks whether pipe has been used or not.

I can almost recreate the successful result I outlined in my question with the following script -- the only thing missing is the pre-prompt message (Going to bring up a prompt). And I've added pipe-args and yargs to show that the piped in data is preserved.

#!/usr/bin/env nodeconst prompts = require("prompts");
const tty = require("tty");
const pipe = require("pipe-args").load();
const argv = require("yargs").argv;
const ttys = require("ttys");

const questions = [0, 1, 2, 3, 4]
  .map(x => ({
    type: "text",
    name: `prompt-${x}`,
    message: "This is a test -- enter something",
    stdin: ttys.stdin
  }));


const onSubmit = function (prompt, answer) {
  console.log("Result", answer); // => { value: 24 }
};

(async () => {
  const response = awaitprompts(questions, { onSubmit });
  console.log(argv);
  ttys.stdin.destroy();
})();

Solution 2:

You can use cat after in a subshell, like this:

(echo"file2.md"; cat) | .myscript.js --f1 file1.md
(echo hello world; cat) | ./prompt-test.js

You can also add exec to do it with one less process:

(echo"file2.md"; execcat) | .myscript.js --f1 file1.md
(echo hello world; execcat) | ./prompt-test.js

You can also put cat on the outside and use -:

cat <(echo"file2.md") - | .myscript.js --f1 file1.md
cat <(echo hello world) - | ./prompt-test.js

Post a Comment for "Get Argument From Pipe But Also Run Prompts?"