Search code examples
node.jstypescriptwaitkeypress

Pause script until user presses enter in Node.JS


I have a script, and it has a little message. I want it to not do anything until the user presses enter. I tried this:

console.log("Welcome to the Roblox cursor backup script!\n This script will backup your current Roblox cursor and replace it with the old 2021 Roblox cursor.\n\n Please make sure you have a Roblox client closed. \n This script is prefixed at /Applications/Roblox.app, if you are non-admin please run the command with the --noadmin flag.\n\n Press enter to continue. \n\n ---------------------------------------------------------");
// if user presses enter in the terminal, continue
process.stdin.on('keypress', function (letter, key) {
    if (key.name === 'return') {
        console.log("User pressed enter/return, continuing...");
    } else{
        // pause the script until the user presses enter
        process.stdin.pause();
    }

});

However, the script instantly continues. How do I make it so that the script doesn't do anything until the user pressed enter/return?

Full source code: https://github.com/Link2Linc/Old-Roblox-Cursor/blob/master/main.ts


Solution

  • You can simply take input from stdin Sample function :

    function waitForKey(keyCode) {
        return new Promise(resolve => {
            process.stdin.on('data',function (chunk) {
                if (chunk[0] === keyCode) {
                    resolve();
                    process.stdin.pause();
                }
            });
        });
    }
    

    Now if you want to wait for enter key :

    await waitForKey(10);