I am writing some code in JavaScript and running it using the command line using the command node filename.js. I want the user to enter input values on the command line and use these values for further process and output.
1 Answer
Use prompts npm package
npm install --save prompts
const prompts = require('prompts');
const questions = [
{
type: 'text',
name: 'dish',
message: 'Do you like pizza?'
},
{
type: prev => prev == 'pizza' ? 'text' : null,
name: 'topping',
message: 'Name a topping'
}
];
(async () => {
const response = await prompts(questions);
})();
4 Comments
Shraddha J
I'm getting error as below: internal/modules/cjs/loader.js:638 throw err; ^ Error: Cannot find module 'prompts'
nico
cd into your project folder & run
npm install --save prompts then try againShraddha J
Yes it did worked. But how can I get values entered by the user?
Shraddha J
Thanks. I got it.
node filename.js --p1 param1 --p2 param2or in the console. i.e. user runs the script the asked for the first param then second and so on?readlinemodule as suggested by @CodeF0x