繁体   English   中英

process.stdout.write()在Node.js readline CLI程序中不起作用

[英]process.stdout.write() not working in Node.js readline CLI program

我正在使用readline模块为Node.js中的应用程序创建命令行界面(CLI)。

问题是我无法向上滚动以查看过去的命令,因为我通常可以在终端中查看。 我的CLI只是一个固定的窗口,如果我在屏幕上打印太多,我会丢失顶部的信息,无法向上滚动查看它。

(我在Mac OSX Mavericks上运行我的程序)

提前致谢。

代码片段:

var readline = require('readline');

var Cli = function () {
    this.txtI = process.stdin;
    this.txtO = process.stdout;

    process.stdout.write('CLI initialized.');

    this.rl = readline.createInterface({input: this.txtI, output: this.txtO });
    this.rl.setPrompt('>>>');
    this.rl.prompt();
    this.rl.on('line', function(line) {
        var input = line.toString().trim();
        if (input) {
            this.txtO.write('cmd: ' + input);
        }
        this.rl.prompt();
    }.bind(this)).on('close', function() {
        this.txtO.write('Have a great day!');
        process.exit(0);
    }.bind(this));
};

new Cli();

将此文件另存为snippet.js并运行

node snippet.js

在终端。

Readline是一个非常棒的模块。 历史已经存在。 可以添加完成。 试试下面的代码段。

var readline = require('readline');

function createCLI(opt) {

    var rl = readline.createInterface({
          input : opt.input,
         output : opt.output,
       terminal : opt.terminal || true,
      completer : opt.completer ||
        function asyncCompleter(linePartial, callback){
          var completion = linePartial.split(/[ ]+/);
          callback(null, [completion, linePartial]);
        }
    });

    rl.on('line', function(line) {
      if( !line.trim() ){  this.prompt();  }
      else { this.write(line); }
    }).on('close', function() {
      this.output.write('\n Have a great day!');
      process.exit(0);
    }).setPrompt(' > ');

    rl.output.write(' CLI initialized\n');
    return rl;
}

var cli = createCLI({
   input : process.stdin,
  output : process.stdout
});

cli.prompt();

它可能正在工作,只是readline覆盖你的线。 尝试输出多行:

process.stdout.write("1\n2\n3\n4\n5");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM