Home > Software engineering >  Wait for user input every time and continue in the loop. Using node js
Wait for user input every time and continue in the loop. Using node js

Time:12-26

I need a node js function that goes through two arrays and waits for user input every time and then continues to loop.

let array = **SOME_ARRAY**; 
let array_2 = **SOME_ARRAY**;
for (let i in array) {
    for (let j in array_2) {
        process.stdin.on('data', data => {
            data = data.toString();
            data = data.replaceAll('\r', '').replaceAll('\n', '');
            console.log(data, array[i], array_2[j]);
        });
    }
}

CodePudding user response:

You could use readline.question with async-await:

const readline = require('readline');

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

    return new Promise(resolve => interface.question("Please provide next input: ", answer => {
        interface.close();
        resolve(answer);
    }))
}


(async () => {

    const array = [1, 2];
    const array2 = [4, 5];
    for (const a of array) {
        for (const b of array2) {
            const data = await readInput();

            // Do something with your data...

            console.log(data, a, b);
        }
    }
})();
  • Related