【问题标题】:How to have syntax highlighting of input text in Node.js REPL?如何在 Node.js REPL 中突出显示输入文本的语法?
【发布时间】:2020-07-23 09:21:13
【问题描述】:

这在 Linux 终端中是可能的,因为有像 fish 这样的 shell 对输入文本使用不同的突出显示。是否有可能在 Node.js 中有这样的东西。还是我需要用这个功能重新实现 readLine 库。

有谁知道如何在 Node.js 中做到这一点?我正在检查fish on GitHub 的代码,似乎该项目使用了NCurses。我可以在 Node.js 中做同样的事情来让 REPL 输入文本是彩色的吗?

编辑

我已经通过@MehdiBelbal 解决方案测试了这段代码:

var readline = require('readline');

var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question("lips> ", function(code) {
  console.log('\ncode is ' + code);
  rl.close();
});

rl._writeToOutput = function _writeToOutput(stringToWrite) {
    rl.output.write(stringToWrite.replace(/define/g, '\u001b[1;34mdefine\x1b[0m'));
};

但是在你输入之后它并没有高亮define这个词,你需要输入空格(或任何字符)并用退格键删除它。

【问题讨论】:

标签: javascript node.js syntax-highlighting read-eval-print-loop ansi-escape


【解决方案1】:

您可以通过覆盖 _writeToOutput 方法来实现这一点 '\x1b[31m' 是控制台红色 unicode 你需要添加 '\x1b[0m' 是重置, 颜色必须停在这个位置:

rl._writeToOutput = function _writeToOutput(stringToWrite) {
    rl.output.write('\x1b[31m'+stringToWrite+'\x1b[0m');
};

颜色 unicodes:

Black: \u001b[30m.
Red: \u001b[31m.
Green: \u001b[32m.
Yellow: \u001b[33m.
Blue: \u001b[34m.
Magenta: \u001b[35m.
Cyan: \u001b[36m.
White: \u001b[37m.

代码示例:

var readline = require('readline');

var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question("code: ", function(code) {
  console.log('\ncode is ' + code);
  rl.close();
});

// force trigger of _writeToOutput on each keystroke
process.stdin.on('keypress', (c, k) => {
    // setTimeout is needed otherwise if you call console.log
    // it will include the prompt in the output
    setTimeout(() => {
        rl._refreshLine();
    }, 0);
});

rl._writeToOutput = function _writeToOutput(stringToWrite) {
    rl.output.write(stringToWrite.replace(/define/g, '\u001b[1;34mdefine\x1b[0m'));
};

键入“define”将其设为蓝色。

【讨论】:

  • 我想设置输入而不是输出的样式。
  • 是的,上面的代码样式用户输入(由用户编写)自己尝试一下。该函数的名称具有误导性 writeToOutput 意味着 readline 将用户击键写入控制台,否则您将看不到您正在输入的内容(如密码什么也不写或 *****)
  • 我想为用户正在编辑的文本而不是输出着色。您发送到输出rl.output.write 是输出而不是rl.input
  • 是的,我了解您需要上面的功能为用户输入着色(在编辑时)
  • 好的,会检查,所以这是 readline 的某种未记录的功能?
【解决方案2】:

如果您指的是控制台,我可以建议扩展名为 Chalk。 使用粉笔的示例:

const chalk = require("chalk");

//...

console.log(chalk.red("Red text, ") + "normal text");

这将以红色记录“红色文本”。

【讨论】:

  • 我想设置输入而不是输出的样式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-20
  • 2014-04-03
  • 2012-08-21
  • 2012-02-22
  • 2019-04-07
相关资源
最近更新 更多