繁体   English   中英

如何在 Node.js REPL 中突出显示输入文本的语法?

[英]How to have syntax highlighting of input text in Node.js REPL?

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

有谁知道如何在 Node.js 中做到这一点? 我正在GitHub 上检查fish的代码,该项目似乎使用了 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'));
};

但它不会在您输入后突出显示单词定义,您需要输入空格(或任何字符)并用退格键删除它。

您可以通过覆盖 _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”以将其显示为蓝色。

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

const chalk = require("chalk");

//...

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

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

暂无
暂无

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

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