Sunday, 15 December 2019

How to differentiate between standard-inputs (via pipe and via prompt) in NodeJS?

My goal: piping standard input from echo to a node file and asking for more input via a prompt. But I need to know which input is from the piping and which one is from the prompt.

The node file x.js looks like this:

const readline = require("readline");

let rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.question("yes or no? (y/n)", answer => {
    console.log("-" + answer + "-");
    rl.close();
});

This one works (A prompt is shown, I enter "hello" and it is written to the console):

> node x.js -hello-

But this does not work (There is no prompt. The piped string is just written to the console.):

> echo "abcdefgh" | node x.js -abcdefgh-

How can I differentiate between those 2 kinds of standard input?



from How to differentiate between standard-inputs (via pipe and via prompt) in NodeJS?

No comments:

Post a Comment