Search code examples
node.jsprompt

In NodeJS, how can I get a password from input without the user's keypresses being echoed to the console?


I'm trying to add a simple setup prompt to my program, where it prompts for some basic details before starting the app for the first time. One of these inputs I need is a password. When I read this password, I want to ensure that (much like when you enter a password for sudo) it doesn't appear in the user's terminal as they type.

How can I do so within NodeJS? I'm looking for something I can drop into the following code.

console.log('Failed to find config file');
// This echoes to the console - how can I do the same thing without the echo?
const password = prompt('Enter a password: ');

I'm happy to install a dependency from NPM if required.


Solution

  • You can use the prompt-sync library to prompt for passwords.

    import createPrompt from 'prompt-sync';
    const prompt = createPrompt({});
    
    // The prompt object's hide method gives a prompt where the input 
    // is hidden
    const password = prompt.hide('Enter a password: ');