清除Node.js readline shell中的终端窗口

mko*_*ala 15 readline node.js coffeescript read-eval-print-loop

我有一个用Coffeescript编写的简单readline shell:

rl = require 'readline'
cli = rl.createInterface process.stdin, process.stdout, null
cli.setPrompt "hello> "

cli.on 'line', (line) ->
  console.log line
  cli.prompt()

cli.prompt()
Run Code Online (Sandbox Code Playgroud)

运行此命令会显示提示:

$ coffee cli.coffee 
hello> 
Run Code Online (Sandbox Code Playgroud)

我希望能够点击Ctrl-L清除屏幕.这可能吗?

我也注意到,我不能打Ctrl-L在任一节点咖啡 REPLs无论是.

我在Ubuntu 11.04上运行.

log*_*yth 29

您可以自己观看按键并清除屏幕.

process.stdin.on 'keypress', (s, key) ->
  if key.ctrl && key.name == 'l'
    process.stdout.write '\u001B[2J\u001B[0;0f'
Run Code Online (Sandbox Code Playgroud)

清除是通过ASCII控制序列完成的,如下所示:http: //ascii-table.com/ansi-escape-sequences-vt-100.php

第一个代码\u001B[2J指示终端自行清除,第二个代码\u001B[0;0f强制光标返回到位置0,0.

注意

keypress事件不再是Node中标准Node API的一部分,>= 0.10.x但您可以使用keypress模块.


小智 5

在MAC终端中,为了清除NodeJS中的控制台,你COMMAND+K就像在谷歌开发者工具控制台中一样,所以我猜测它会在Windows上CTRL+K.


ale*_*son 5

这是唯一可以清除屏幕滚动历史记录的答案。

function clear() {
  // 1. Print empty lines until the screen is blank.
  process.stdout.write('\033[2J');

  // 2. Clear the scrollback.
  process.stdout.write('\u001b[H\u001b[2J\u001b[3J');
}

// Try this example to see it in action!
(function loop() {
  let i = -40; // Print 40 lines extra.
  (function printLine() {
    console.log('line ' + (i + 41));
    if (++i < process.stdout.columns) {
      setTimeout(printLine, 40);
    }
    else {
      clear();
      setTimeout(loop, 3000);
    }
  })()
})()
Run Code Online (Sandbox Code Playgroud)
  • 第一行确保可见行始终被清除。

  • 第二行确保清除滚动历史记录。