default to original string if you're not in a headless environment (like a browser).

makes console.log('hello'.red) work.
This commit is contained in:
Dustin Diaz (@ded) 2011-03-07 18:09:07 -08:00
parent b6ff10236a
commit e49356a4c2

View File

@ -24,10 +24,12 @@ THE SOFTWARE.
*/ */
// prototypes the string object to have additional method calls that add terminal colors // prototypes the string object to have additional method calls that add terminal colors
var isHeadless = (typeof module !== 'undefined');
['bold', 'underline', 'italic', 'inverse', 'grey', 'yellow', 'red', 'green', 'blue', 'white', 'cyan', 'magenta'].forEach(function (style) { ['bold', 'underline', 'italic', 'inverse', 'grey', 'yellow', 'red', 'green', 'blue', 'white', 'cyan', 'magenta'].forEach(function (style) {
Object.defineProperty(String.prototype, style, { Object.defineProperty(String.prototype, style, {
get: function () { get: function () {
return stylize(this, style); // default to 'this' for those running console.log() from a browser
return isHeadless ? stylize(this, style) : this;
} }
}); });
}); });
@ -36,6 +38,9 @@ THE SOFTWARE.
// rainbow will apply a the color spectrum to a string, changing colors every letter // rainbow will apply a the color spectrum to a string, changing colors every letter
Object.defineProperty(String.prototype, 'rainbow', { Object.defineProperty(String.prototype, 'rainbow', {
get: function () { get: function () {
if (!isHeadless) {
return this;
}
var rainbowcolors = ['red','yellow','green','blue','magenta']; //RoY G BiV var rainbowcolors = ['red','yellow','green','blue','magenta']; //RoY G BiV
var exploded = this.split(""); var exploded = this.split("");
var i=0; var i=0;