1. HTML 实体
1.1. 是什么?
HTML 实体是一段以连字号(&)开头、以分号(;)结尾的文本。实体常常用于显示保留字符(这些字符会被解析为 HTML 代码)和不可见的字符(如“不换行空格”)。你也可以用实体来代替其他难以用标准键盘键入的字符。
图1:几个例子
1.2. html-entities
用途:HTML 实体编码、解码库。
安装:
npm install html-entities
示例:
import { AllHtmlEntities } from 'html-entities';
const entities = new AllHtmlEntities();
console.log(entities.encode('<>"&©®∆')); // <>"&©®∆
console.log(entities.encodeNonUTF('<>"&©®∆')); // <>"&©®∆
console.log(entities.encodeNonASCII('<>"&©®∆')); // <>"&©®∆
console.log(entities.decode('<>"&©®')); // <>"&©®
2. ANSI 转义序列
2.1. 是什么?
ANSI 转义序列(ANSI escape sequence)是一种用于控制终端输出的色彩、样式、光标位置以及控制终端行为的特殊序列。
示例1:入门
示例2:进阶
function printSingleLine(text){
const MOVELEFT = '\033[1000D';
const CLEARLINE = '\033[K';
const RED = (text) => '\033[31m' + text + '\033[39m';
process.stdout.write(MOVELEFT+CLEARLINE);
process.stdout.write(RED(text));
}
class ProgressBar{
constructor(labelValue, total, totalCellNums = 50) {
this.labelValue = labelValue;
this.total = total;
this.totalCellNums = totalCellNums;
}
render(current){
const curPercent = (current / this.total).toFixed(4);
const curCellNums = Math.floor(curPercent * this.totalCellNums);
let cells = "";
for(let i=0; i<this.totalCellNums; i++){
if(i<curCellNums){
cells += '█';
}else{
cells += '░';
}
}
const cmdTxt = `${this.labelValue}: ${(100*curPercent).toFixed(2)}% ${cells} ${current}/${this.total}`;
printSingleLine(cmdTxt)
}
}
function app(){
const total = 200;
let current = 0;
const progressBar = new ProgressBar("下载进度", total)
const download = () => {
if (current <= total) {
progressBar.render(current++);
setTimeout(function (){
download();
}, 50)
}
};
download();
}
app();
2.2. chalk
chalk(粉笔),即利用 ANSI 转义序列特性,产生带样式的控制台文本。
安装:
npm install --save chalk
示例:
2.3. ansi-html
可用于将 ANSI 序列转换为 HTML。
安装:
npm install ansi-html
示例:
import chalk from "chalk";
import ansiHTML from 'ansi-html';
export default function printMe(){
const text = chalk.blue('Hello') + ' World' + chalk.red('!');
console.log(JSON.stringify(text));
console.log(text);
console.log(ansiHTML(text));
}
参考:
--------------------------------------HTML 实体 Entity: https://developer.mozilla.org/zh-CN/docs/Glossary/Entity Named character references: https://html.spec.whatwg.org/multipage/named-characters.html#named-character-references HTML entity encoder/decoder: https://mothereff.in/html-entities html-entities: https://github.com/mdevils/html-entities#readme --------------------------------------Ansi 转义序列 ANSI Escape sequences: http://ascii-table.com/ansi-escape-sequences.php ANSI Colors: https://mudhalla.net/tintin/info/ansicolor/