How to add two numbers in console using Node.js ?
Last Updated :
26 Oct, 2021
In this article, we will see how to add two numbers in the console using NodeJS. For this purpose, we need to know about a node package called prompt. It helps to take user input from the console. We would use its method prompt.get() to take user input.
Create NodeJS Application: Initialize the NodeJS application using the following command:
npm init
Module Installation: Install the prompt module using the following command.
npm install prompt
Implementation: Create an app.js file and write down the following code in it.
app.js
const prompt = require( "prompt" );
function add() {
prompt.start();
prompt.get([ "num1" , "num2" ],
function (err, res) {
if (err) {
console.log(err);
} else {
var sum = parseFloat(res.num1)
+ parseFloat(res.num2);
console.log( "Sum of " + res.num1
+ " and " + res.num2 + " is " + sum);
}
});
}
add();
|
Step to run the application: Run the app.js file using the following command.
node app.js
Output: Now enter the user input and view output in the console.
output
So this is how you can add two numbers in the console using nodeJs. Prompts help us to take input from users. It also supports validation and defaults over the input.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...