Node.js Javascript random color print

Im trying to use the colors javascript module https://github.com/Marak/colors.js

to print a random color in terminal using node.js. The random generator works, but something with the period messes up the syntax and will not print the color correctly.

var colors = require('colors');



 Array.prototype.random = function (length) {
       return this[Math.floor((Math.random()*length))];
 }

 var color = ['.yellow', '.cyan', '.magenta', '.red', '.green', '.blue', '.rainbow', '.zebra']
 var rcolor = color.random(color.length)

console.log(rcolor + 'rcolor')

You need to change your code a little bit

var colors = require('colors');

Array.prototype.random = function (length) {
  return this[Math.floor((Math.random()*length))];
}

var color = ['yellow', 'cyan', 'magenta', 'red', 'green', 'blue', 'rainbow', 'zebra']
var rcolor = color.random(color.length)

console.log(("Print in color " + rcolor)[rcolor]);

This is because colors add prototypes to the String class, so in JavaScript you can always execute a property method on a object using [], if can use use it in every string like this:

console.log("Hello colors!"[rColor]);

First, remove all of the periods. Then you should be able to do something like this:

console.log(colors[randomColor]("Hello, world!"));

Or alternatively:

console.log("Hello, world!"[randomColor]);

This works because a.b is equivalent to a["b"], except in the latter, you could replace "b" with an expression. Since the colors module supports, say, colors.red(someString) and someString.red, we can simple change it to use the [] syntax and put in a variable there.

The following code (not far off what you have) prints a random color from the given list.

var colors = require("colors");

Array.prototype.random = function () {
    return this[Math.floor(Math.random() * this.length)];
};

var colorsList = [".yellow", ".red", ".blue"];
var rColor = colorsList.random();

console.log(colorsList);
console.log(rColor);

It includes colors@0.6.0-1, but I don't know why you need it for what you have written.