簡體   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