Node.js in Action: Work With Colors Module

This is the node.js in action article series. We have already covered many topics in node.js in this series. You can read them here.

In this article we will work with another interesting module, the color module. The color module uses the popular color.js. Since the color module is not a built-in module of node.js, we need to install it using the node package manager.

Before that I will request that you check whether node is set up and running in your application. To install the colors module in an application, just navigate to the proper directory and fire the following command.

npm install colors

Once the command has executed successfully, you will find the following screen. In my case it's showing that the colors module was successfully installed in the application and is ready for use.

npm install colors

The beauty of the colors module is that we can beautify the output with various colors. Here is the link to the colors module in NPM.

Colour

Let's implement a few small examples to understand how the colors module works with node.js. Have a look at the following example.

var http = require('http');

var colors = require('colors');

var server = http.createServer(function (req,res) {

      console.log('This String Will Display RED'.red);

});

server.listen(9090);

In the second line we are loading the colors module into our application. After loading the colors module, we can use it in our application. Have a look at the body of the createServer() function. The module will provide freedom to use a color associated with the (.) property of the object.

Like, “sring”.colorname

In this example we are using the red color by giving (.) after the object. Here is the sample output.

red color

Not only red, we can provide many colors in the same way. Here is the uses of the colors module.

Usage

This package extends the global String prototype with additional getters that apply terminal colors to your texts. The available styles are:
  • Emphasis: bold, italic, underline, inverse
  • Colors: yellow, cyan, white, magenta, green, red, grey, blue
  • Sequencers: rainbow, zebra, random

So, let's try another example. Here is some sample code.

var http = require('http');

var colors = require('colors');

var server = http.createServer(function (req,res) {            

    console.log('hello'.green); // outputs green text

    console.log('i like cake and pies'.underline.red) // outputs red underlined text

    console.log('inverse the color'.inverse); // inverses the color

    console.log('OMG Rainbows!'.rainbow); // 

});

server.listen(9090);

The output of this example is.

Output

Conclusion

Using the color module we can decorate output from node.js. It will result in writing more HTML code to decorate output.

Up Next
    Ebook Download
    View all
    Learn
    View all