79294995

Date: 2024-12-19 16:41:44
Score: 0.5
Natty:
Report link

Basically, a function like input() that exists in Python is not available in NodeJs, on the other hand, there is no clear and simple method to get data from the input.

But in general, this goal can be achieved in two ways:

  1. Using internal modules available in NodeJs.

This method requires a lot of configuration, so for someone new to NodeJs, it may be too complicated and you may not get the result you want.

  1. In the second method, it is better to use external modules (packages).

In this way, the complications of this work are minimized and you can reach this goal very easily.

For the second way, there are many packages, one of them is Softio, which has the same methods you mentioned.

To use Softio, just follow the instructions below step by step:

  1. First you need to install this package. Just run the following command in your project path:
npm install softio

There is no need to worry, when you have installed Node Js, you have also installed npm and you can run the above command.

  1. Then it is enough to write the following code to get the data from user:
const softio = require( 'softio' );

async function main() {
    const name = await softio.input( 'Enter your name: ' );
    const age = await softio.readNumber( 'Enter your age: ' );

    if ( age < 18 ) {
        softio.write( `Sorry, your age is under 18 :(` );
        return;
    }

    softio.input( 'welcome.' );
}
main();

The important thing is that reading data from stdin (the same as getting data from the user) in NodeJs is executed concurrently, so to manage this concurrency you must use the keyword 'await', on the other hand, to use this keyword you must You must be inside a function that is 'async'. This point is related to concurrency management in JavaScript.

Reasons:
  • Blacklisted phrase (1): :(
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: Arya Fardmanesh