Skip to content

Instantly share code, notes, and snippets.

@luobotang
Created November 15, 2017 08:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luobotang/a1db8e7b2f76c116951b2cf43214c990 to your computer and use it in GitHub Desktop.
Save luobotang/a1db8e7b2f76c116951b2cf43214c990 to your computer and use it in GitHub Desktop.
控制台文本格式化工具
var colors = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white']
function F(text) {
this.text = text
this.attr = 0
this._color = 0
this._bgColor = 0
}
F.prototype.toString = function() {
var chars = ''
if (this.attr > 0) {
chars += this.attr
}
if (this._color > 0) {
chars = chars ? chars + ';' + this._color : this._color
}
if (this._bgColor > 0) {
chars = chars ? chars + ';' + this._bgColor : this._bgColor
}
if (chars) {
return `\x1b[${chars}m${this.text}\x1b[0m`
} else {
return this.text
}
}
F.prototype.bold = function() {
this.attr = 1
return this
}
F.prototype.underscore = function() {
this.attr = 4
return this
}
F.prototype.blink = function() {
this.attr = 5
return this
}
F.prototype.reverse = function() {
this.attr = 7
return this
}
F.prototype.hidden = function() {
this.attr = 8
return this
}
F.prototype.color = function(color) {
var i = colors.indexOf(color)
if (i === -1) this._color = 0
else this._color = 30 + i
return this
}
F.prototype.bgColor = function(color) {
var i = colors.indexOf(color)
if (i === -1) this._bgColor = 0
else this._bgColor = 40 + i
return this
}
module.exports = F
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment