'Ask users to input value for npm script

I have an npm script, which is run like that:

npm run start:local -- -target.location https://192.1.1.1:8052/

The URL param is the local IP of a user.

What I would love to have is to ask users to input this value, because it's different for everybody.

Is it possible? Would be great to do it with vanila npm scripts.

npm


Solution 1:[1]

Simply speaking, an npm script will run the desired command in your shell environment.

In a shell script, the arguments passed can be accessed using $N where N = Position of the argument.

Talking about your case, the command you want to run is npm run start:local -- -target.location USER_INPUT USER_INPUT needs to replaced with the argument that the user has passed. Assuming that the user will pass location as the first argument to the script, it can be accessed using $1.

I have created this gist to demonstrate the same.

enter image description here

As you can clearly see, I have defined start:local to access the first argument and then, pass it to the start script which then echoes out the passed in argument.

enter image description here

UPDATE: Here is the script for ASKING a value from a user in a prompt format. enter image description here

Basically, first I am asking for user input then, storing the same in a variable and passing the variable as an argument to npm start

enter image description here

References

Solution 2:[2]

Example: If we want to run below three commands in sequence with userinput

git add .
git commit -m "With git commit message at run time"
git push

Add below command in your package.json file under the scripts

"gitPush": "git add . && echo 'Enter Commit Message' && read message && git commit -m \"$message\" && git push"

enter image description here

And run commands via npm run gitPush

enter image description here

References: ask-users-to-input-value-for-npm-script

Solution 3:[3]

Use Node's readline? it has methods for interactive IO.

Solution 4:[4]

If you're trying to ask for users to input ther response you could do something like this.

const readline = require("readline");

const reader = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    error: process.stderr
});

const ask = (message, default_value = null) => new Promise(resolve => {
    reader.question(message, (response)=>{
        return resolve(response.length >= 1 ? response : default_value);
    });
});

(()=>{
    let ip = await ask(`Please enter your public ip: `);
})();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Sergey Pogodin
Solution 4 Eduardo Jiménez