清除Node.js readlineshell中的terminal窗口

我有一个用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() 

运行这将显示一个提示:

 $ coffee cli.coffee hello> 

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

我也注意到,我无法在节点咖啡 REPL中Ctrl-L

我在Ubuntu 11.04上运行。

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

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

清除操作使用ASCII控制序列,如下所示: http : //ascii-table.com/ansi-escape-sequences-vt-100.php

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

注意

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

在MACterminal中,要清除NodeJS中的控制台,就像在Google Developer Tools Console中一样点击COMMAND+K ,所以我猜测在Windows上它是CTRL+K

回应@loganfsmyth评论他的回答(感谢编辑!)。

我一直在寻找这里和那里,除了奇妙的按键模块,还有一个核心模块,使得可以创build一个具有所有标准terminal行为的cli (我们今天给予的所有东西,如历史,选项提供一个自动- 完整的function和input事件,如keypress在那里)。

该模块是readline ( 文档 )。 好消息是,所有标准行为已经完成了,所以不需要附加事件处理程序(即历史logging, 按Ctrl + L清除屏幕,如果你提供了自动完成function的人,它会在Tab按下)。

只是一个例子

 var readline = require('readline') , cli = readline.createInterface({ input : process.stdin, output : process.stdout }); var myPrompt = ' > myPropmt ' cli.setPrompt(myPrompt, myPrompt.length); // prompt length so you can use "color" in your prompt cli.prompt(); // Display ' > myPrompt ' with all standard features (history also!) cli.on('line', function(cmd){ // fired each time the input has a new line cli.prompt(); }) cli.input.on('keypress', function(key){ // self explanatory // arguments is a "key" object // with really nice properties such as ctrl : false process.stdout.write(JSON.stringify(arguments)) }); 

真的很好的发现。

我使用的节点版本是v0.10.29 。 我一直在查看更新日志,并且自2010年以来一直存在(提交10d8ad )。

也试试:

 var rl = require('readline'); rl.cursorTo(process.stdout, 0, 0); rl.clearScreenDown(process.stdout); 

Vorpal.js使这样的事情变得非常简单。

对于具有clear命令的交互式CLI以及应用程序上下文中的REPL,请执行以下操作:

 var vorpal = require('vorpal')(); var repl = require('vorpal-repl'); vorpal .delimiter('hello>') .use(repl) .show(); vorpal .command('clear', 'Clears the screen.') .action(function (args, cb) { var blank = ''; for (var i = 0; i < process.stdout.rows; ++i) { blank += '\n'; } vorpal.ui.rewrite(blank); vorpal.ui.rewrite(''); cb(); }); 

您可以使用console.log()和转义序列清除屏幕。

 cli.on 'line', (line) -> if line == 'cls' console.log("\033[2J\033[0f") else console.log line cli.prompt() 

这是清除屏幕滚动历史logging的唯一答案。

 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); } })() })() 
  • 第一行确保可见行总是被清除。

  • 第二行确保滚动历史logging被清除。