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?

1 Answers1

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();
});
nah0131
  • 329
  • 1
  • 8
  • Which version of nodejs are you using? – Amitesh Kumar Feb 24 '22 at 19:37
  • 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. (C:\Users\bhanu\OneDrive\Desktop\node_pro\abcd.js:8:56) – Amitesh Kumar Feb 24 '22 at 19:43
  • 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 – nah0131 Feb 25 '22 at 08:03