javascriptnode.jskeyboardkeypressreadline

Node.js process/readline on keypress listener prevents the app from ever ending on its own


I'm trying to:

Here's my function:

export async function inkey_promise() {
    console.log('Press any key...');

    return new Promise((resolve) => {
        readline.emitKeypressEvents(process.stdin);
        process.stdin.setRawMode(true);
        const listener = (str, readline_key) => {
            process.stdin.setRawMode(false);
            process.stdin.resume();
            console.log(`RETURNING: `, readline_key);
            return resolve(readline_key);
        };
        process.stdin.once('keypress', listener);
    });
}

And I call it like:

const key_info = await inkey_promise();

Problem:

After pressing a key:

So it seems that there's something else I need to do to fully return the process/stdin/keyboard back to its default behaviour/state?


Solution

  • import readline from 'readline';
    
    type Args_tui_prompt_inkey = {
        echo_debug: boolean;
    };
    
    export async function tui_prompt_inkey(args?: Args_tui_prompt_inkey): Promise<Output_tui_prompt_inkey> {
        return new Promise((resolve) => {
            const rl = readline.createInterface({
                input: process.stdin,
                output: process.stdout,
            });
            const listener = (_arg1: never, rkey: readline.Key) => {
                rl.close();
                if (args?.echo_debug) console.log(`rkey is: `, rkey);
                resolve({
                    rkey: rkey,
                });
            };
            // using ['input'] to suppress TS errors
            rl['input'].once('keypress', listener);
            rl['input'].setRawMode(true);
            rl['input'].resume();
        });
    }
    
    type Output_tui_prompt_inkey = {
        rkey: readline.Key;
    };