Search code examples
node.js

How to ask response in next line of the question with node readline?


I need to get response from the read line interface, everything works fine but I would like to enter the answer next line after to the question but now I'm able to enter answer along with the question.

async function IsAgreed() {
    const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
    let options = ['yes', 'y', 'YES', 'Y'];
    let response = await rl.question('Do you agree to execute ?');
    
    return options.includes(response);
}

Output:

Do you agree to execute ?| <-- cursor is here

Expected Output:

Do you agree to execute ?
| <-- I need to insert cursor here

I'm new to coding, any idea would be help full for me.


Solution

  • Just add \n escape character at the end of question. \n will insert new line so you can enter the response in the next line of the question.

    async function IsAgreed() {
        const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
        let options = ['yes', 'y', 'YES', 'Y'];
        let response = await rl.question('Do you agree to execute ?\n'); // Here ✅
        
        return options.includes(response);
    }
    

    Don't forget to close the readline interface rl.close() after all actions.