Haris ur Rehman
Haris ur Rehman

Reputation: 2663

Send a string and Enter key to a Node.js script from command line

I am running a Node.js script in Linux that prompts (via lib) user for a code. I get the process id of the script:

pgrep -f test.js 

and then pass it the code with a new line to simulate Enter key:

echo -e "1234\n" > /proc/88888/fd/0

The code 1234 gets passed, a new line is added as well, but it didn't trigger Enter key and the script does not proceed. However, when I manually press Enter key in shell, the script does recognise the Enter key. So the question is how can I reliably send Enter key to another process/script?

Following is the code of test.js script:

inquirer = require('inquirer');

async function plztest() {

let { code } = await inquirer.prompt([
    {
        type: 'input',
        name: 'code',
        message: 'Enter code',
    },
]);
console.log(code);
process.exit();
};
      
plztest();

Upvotes: 3

Views: 1355

Answers (1)

Yash Kumar Verma
Yash Kumar Verma

Reputation: 9620

Thank you for providing the code snippet of the javascript file, I've got a solution for the same.

The problem

is that you are a bit confused about the usage of pipes and redirections.

  • Pipe | is used to pass output to another program or utility.
  • Redirect > is used to pass output to either a file or stream.

A more detailed answer about pipes and redirections is given here

The Solution

Since now we know that we need to use pipes here, something like this would solve the problem.

echo -e "1234" | /proc/88888/fd/0

Tests

I ran the script you have provided in the question, and the following are the output screenshots. Local Screenshots of script

Upvotes: 1

Related Questions