Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js multiline input

I'd like to prompt the user for input, let the user enter multiple lines of text, hitting enter between each line, then terminate the input by pressing CTRL+D or some such thing.

With "keypress", I can catch the EOF, but I would have to handle all the echoing, backspace handling, terminal escape sequences, etc. manually. It would be much better if I could use "readline", but somehow intercept the CTRL+D (EOF) with "keypress", but I'm not sure how I would go about that.

like image 350
Rich Remer Avatar asked Oct 13 '14 23:10

Rich Remer


1 Answers

You can use the line and close events:

var readline = require('readline');

var input = [];

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.prompt();

rl.on('line', function (cmd) {

    input.push(cmd);
});

rl.on('close', function (cmd) {

    console.log(input.join('\n'));
    process.exit(0);
});
like image 90
Gergo Erdosi Avatar answered Oct 24 '22 21:10

Gergo Erdosi