1

I have to get 1st input of the Number of Test Cases:

if the test case is got input of 1, Then I need to get 2 more inputs.

if the test case is got input of 2, Then I need to get 4 more inputs.

Is it possible to use STDIN for dynamic input using 1st input in NodeJS?

3
  • 2
    Yes, it's possible! Commented Feb 23, 2022 at 18:15
  • Sure, why not? You can code it to do pretty much whatever you want. Commented Feb 23, 2022 at 18:19
  • Does this answer your question? Node detect child_process waiting to read from stdin Commented Feb 23, 2022 at 18:22

1 Answer 1

1

Sure, this is possible. In NodeJS, you could use the built-in readline module. Nothing prevents you from building logic so that a dynamic number of inputs are read. For example, something like this might help you:

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.question("How many entries do you need to create? ").then(async answer => {
    const numberOfEntries = Number(answer);

    // Validate input
    if (!Number.isInteger(numberOfEntries) || numberOfEntries < 1)
        throw new Error("Invalid number of entries");

    // Read dynamic number of inputs
    const entries = [];
    for (let i = 0; i < numberOfEntries; i++) {
        const foo = await rl.question("Foo? ");
        const bar = await rl.question("Bar? ");
        
        entries.push({foo, bar});
        console.log(`Entry ${i} with foo = ${foo} and bar = ${bar}`);
    }
 
    rl.close();
});
Sign up to request clarification or add additional context in comments.

3 Comments

Which version of nodejs are you using?
I am getting this error - rl.question("How many entries do you need to create? ").then(async answer => { ^ TypeError: Cannot read properties of undefined (reading 'then') at Object.<anonymous> (C:\Users\bhanu\OneDrive\Desktop\node_pro\abcd.js:8:56)
The readline module has one callback-version and one promise-version. This example is using the promise-version (obviously) so make sure to import readline/promises

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.