Pass command-line arguments in node js:
This section helps you to learn how to pass command-line arguments in node js. This chapter will be very useful where the user has to pass some information or parameters to the application by the console.
Let us create a puzzle that accepts the inputs from the command line and makes some logic on data.
The puzzle displays the set of questions and asks the answer. Once all questions have been finished then it says bye.
Create a file server.js and put the below code
server.js
var questions=[ 'what is your name?\n', 'what is your hobby?\n', 'what is your fav?\n', ]; let answers=[]; function ask(i) { process.stdout.write(`\n ${questions[i]} \n`); process.stdout.write(''); } process.stdin.on('data',function(data) { console.log('\n Received data : '+data); console.log('All answers : '+answers); answers.push(data.toString().trim()); if(answers.length<questions.length) { ask(answers.length); } else{ process.exit(); } } ); process.on('exit', function() { process.stdout.write('Good bye....\n'); }); ask(0); console.log("End of the file"); run the command: node server //output what is your name? End of the file John Received data : John All answers : what is your hobby? Watching movies Received data : Watching movies All answers : John what is your fav? cricket Received data : cricket All answers : John,Watching movies Good bye....
So by playing the above puzzle command line args are very important in console-based applications.
Please comment if you are facing problem while running the puzzle
One thought on “Pass command line arguments in node js”
Comments are closed.