Clear terminal window in Node.js readline shell

后端 未结 7 867
长情又很酷
长情又很酷 2021-01-31 05:41

I have a simple readline shell written in Coffeescript:

rl = require \'readline\'
cli = rl.createInterface process.std         


        
7条回答
  •  [愿得一人]
    2021-01-31 06:18

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

提交回复
热议问题