I am writing another simple Node.js program for beginners. This Node.js program calculates the area of a rectangle based on user input for its width and height.
This will prompt the user to enter the width and height of the rectangle. After the user provide valid positive numeric values for both width and height, it will calculate and display the area of the rectangle.
Let’s see the program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); function calculateRectangleArea(width, height) { return width * height; } function getUserInput() { rl.question('Enter the width of the rectangle: ', (width) => { rl.question('Enter the height of the rectangle: ', (height) => { const numericWidth = parseFloat(width); const numericHeight = parseFloat(height); if (isNaN(numericWidth) || isNaN(numericHeight) || numericWidth <= 0 || numericHeight <= 0) { console.log('Invalid input. Please enter positive numeric values for width and height.'); } else { const area = calculateRectangleArea(numericWidth, numericHeight); console.log(`The area of the rectangle is: ${area}`); } rl.close(); }); }); } getUserInput(); |
Program Output:
if you enter 5
for width and 8
for height, the output will be:
1 2 3 |
Enter the width of the rectangle: 5 Enter the height of the rectangle: 8 The area of the rectangle is: 40 |
This program is useful for beginners, It demonstrates how to use the readline module to get user input and perform simple calculations based on that input.