Node.js – First application

By | 05/08/2019

In this post, we will see how to create a one simple console application (sum of two values) using Node.js.

We run Visual Studio Code, open a new Terminal, select the folder where we want to create the project and we run the command npm init.
Then, we install a module called readline-sync, using the command npm install readline-sync, for getting input from the console.

Now, we create a file called index.js where we’ll do these three steps:
1) define a method to add two values
2) get input from the console
3) display the result.

// ******************STEP 1
// definition of a function to add two values
function add(val1, val2){
    return (val1 + val2);
}

// ******************STEP 2
// definition of a constant to use for reading data from console
const readline = require('readline-sync');
// input data
let inputVal = readline.question("Enter two values, separated by a comma:  ");
// transformation of the string into array of numbers
// for this example the input MUST be correct
var Values = inputVal.split(",").map(Number);

// ******************STEP 3
// Calling to the add method and display the result
console.log("The value of sum is: " + add(Values[0],Values[1]));



Now, using the command node index.js, we run the application:



Leave a Reply

Your email address will not be published. Required fields are marked *