'Is there way take dynamic input using stdin in NodeJS?

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?



Solution 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();
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 nah0131