Node.js multiline input

人走茶凉 提交于 2020-08-24 05:56:46

问题


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.


回答1:


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);
});


来源:https://stackoverflow.com/questions/26350256/node-js-multiline-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!