Node.js 多行输入

问题描述 投票:0回答:2

我想提示用户输入,让用户输入多行文本,在每行之间按 Enter,然后按 CTRL+D 或类似的东西终止输入。

使用“按键”,我可以捕获 EOF,但我必须手动处理所有回显、退格处理、终端转义序列等。如果我可以使用“readline”,但以某种方式用“keypress”拦截 CTRL+D (EOF),那就更好了,但我不确定我会如何去做。

node.js keypress readline eof command-line-interface
2个回答
20
投票

您可以使用

line
close
事件:

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

1
投票

@inquirer/editor
包做得很好

它打开用户的默认编辑器进行输入

例如

import editor from '@inquirer/editor';

const story = await editor({
  message: "Tell me a story",
  waitForUseInput: true,
  postfix: '.md',
})

https://www.npmjs.com/package/@inquirer/editor

© www.soinside.com 2019 - 2024. All rights reserved.