事件: 'line'
function (line) {}
input 输入流收到 \n 后触发,通常因为用户敲回车或返回键。这是监听用户输入的好办法。
监听 line 的例子:
- rl.on('line', function (cmd) {
- console.log('You just typed: '+cmd);
- });
复制代码 事件: 'pause'function () {} 暂停 input 输入流后,会触发这个方法。 当输入流未被暂停,但收到 SIGCONT 也会触发。 (详见 SIGTSTP 和 SIGCONT 事件) 监听 pause 的例子: - rl.on('pause', function() {
- console.log('Readline paused.');
- });
复制代码 事件: 'resume'function () {} 恢复 input 输入流后,会触发这个方法。 监听 resume 的例子: - rl.on('resume', function() {
- console.log('Readline resumed.');
- });
复制代码 事件: 'close'function () {} 调用 close() 方法时会触发。 当 input 输入流收到 "end" 事件时会触发。一旦触发,可以认为 Interface 实例结束。例如当input 输入流收到 ^D,被当做 EOT。 如果没有SIGINT 事件监听器,当input 输入流接收到^C(被当做SIGINT),也会触发这个事件。 事件: 'SIGINT'function () {} 当 input 输入流收到 ^C 时会触发, 被当做SIGINT。如果没有SIGINT 事件监听器,当input 输入流接收到 SIGINT(被当做SIGINT),会触发 pause 事件。 监听 SIGINT 的例子: - rl.on('SIGINT', function() {
- rl.question('Are you sure you want to exit?', function(answer) {
- if (answer.match(/^y(es)?$/i)) rl.pause();
- });
- });
复制代码 事件: 'SIGTSTP'function () {} Windows 里不可用 当 input 输入流收到 ^Z 时会触发,被当做SIGTSTP。如果没有SIGINT 事件监听器,当input 输入流接收到 SIGTSTP,程序将会切换到后台。 当程序通过 fg 恢复,将会触发 pause 和 SIGCONT 事件。你可以使用两者中任一事件来恢复流。 程切换到后台前,如果暂停了流,pause 和 SIGCONT 事件不会被触发。 监听 SIGTSTP 的例子: - rl.on('SIGTSTP', function() {
- // This will override SIGTSTP and prevent the program from going to the
- // background.
- console.log('Caught SIGTSTP.');
- });
复制代码 事件: 'SIGCONT'function () {} Windows 里不可用 一旦 input 流中含有 ^Z并被切换到后台就会触发。被当做SIGTSTP,然后继续执行 fg(1)。程切换到后台前,如果流没被暂停,这个事件可以被触发。 监听 SIGCONT 的例子: - rl.on('SIGCONT', function() {
- // `prompt` will automatically resume the stream
- rl.prompt();
- });
复制代码 例子: Tiny CLI以下的例子,展示了如何所有这些方法的命令行接口: - var readline = require('readline'),
- rl = readline.createInterface(process.stdin, process.stdout);
- rl.setPrompt('OHAI> ');
- rl.prompt();
- rl.on('line', function(line) {
- switch(line.trim()) {
- case 'hello':
- console.log('world!');
- break;
- default:
- console.log('Say what? I might have heard `' + line.trim() + '`');
- break;
- }
- rl.prompt();
- }).on('close', function() {
- console.log('Have a great day!');
- process.exit(0);
- });
复制代码 readline.cursorTo(stream, x, y)在TTY 流里,移动光标到指定位置。 readline.moveCursor(stream, dx, dy)在TTY 流里,移动光标到当前位置的相对位置。 readline.clearLine(stream, dir)清空 TTY 流里指定方向的行。dir 是以下值: - -1 - 从光标到左边
- 1 - 从光标到右边
- 0 - 整行
readline.clearScreenDown(stream)清空屏幕上从当前光标位置起的内容。
|