Clear terminal window in Node.js readline shell

2019-03-08 16:04发布

问题:

I have a simple readline shell written in Coffeescript:

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()

Running this displays a prompt:

$ coffee cli.coffee 
hello> 

I would like to be able to hit Ctrl-L to clear the screen. Is this possible?

I have also noticed that I cannot hit Ctrl-L in either the node or coffee REPLs either.

I am running on Ubuntu 11.04.

回答1:

You can watch for the keypress yourself and clear the screen.

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

Clearing is done with ASCII control sequences like those written here: http://ascii-table.com/ansi-escape-sequences-vt-100.php

The first code \u001B[2J instructs the terminal to clear itself, and the second one \u001B[0;0f forces the cursor back to position 0,0.

Note

The keypress event is no longer part of the standard Node API in Node >= 0.10.x but you can use the keypress module instead.



回答2:

In the MAC terminal, to clear the console in NodeJS, you just hit COMMAND+K just like in Google Developer Tools Console so I'm guessing that on Windows it would be CTRL+K.



回答3:

On response to @loganfsmyth comment on his answer (thanks for the edit!).

I have been looking here and there and, besides of the wonderfull keypress module, there is a core module that makes possible to create a cli with all standard terminal behavior (all things we give for granted today such as history, options to provide an auto-complete function and input events such as keypress are there).

The module is readline (documentation). The good news is that all the standar behaviour is already done for us so there is no need to attach event handlers (i.e. history, clearing the screen on Ctrl+L, man if you provided the auto complete function it'll be on Tabpress).

Just as an example

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

Really good discovery.

The node version I'm using is v0.10.29. I have been looking at the changelog and it was there since 2010 (commit 10d8ad).



回答4:

You can clear screen using console.log() and escape sequences.

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


回答5:

Try also:

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


回答6:

Vorpal.js makes things like this really easy.

For an interactive CLI with a clear command as well as a REPL within the context of your application, do this:

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


回答7:

This is the only answer that will clear the screen AND scroll history.

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);
    }
  })()
})()
  • The first line ensures the visible lines are always cleared.

  • The second line ensures the scroll history is cleared.