Search code examples
node.jsterminalconsoleread-eval-print-loopchalk

Adding color to repl prompt (node)


I find that adding color to the prompt in repl really helps to separate the outputs. I achieved this by using NPM's chalk, but this adds a bunch of space between the prompt and the cursor.

var term = repl.start({
    prompt: chalk.blue('goose> '),
    eval: function(cmd, context, filename, cb){
        ...
    }
});

The prompt comes out like this ('|' is the cursor):

goose>              |

Any ideas on how to fix?


Solution

  • It turns out to be very simple:

    var prompt = 'My fancy prompt >>> ';
    rl.setPrompt(chalk.blue(prompt), prompt.length);
    

    You need to specify the count of characters because readline doesn't understand that escape sequences are really displayed as zero width.

    (This is based on Felix's answer.)