Open In App

Explain Colors Module in Node.js

The colors module is used to style and color the NodeJS console. It is a nice library for better interaction with your node.js project. Generally what we see is the simple text on the terminal but with this module, we can custom style according to our needs and the conventions i.e. we can change the color of the warning text to be red or we can underline the important keyword, etc.  

In this article, we are going to discuss the step-by-step approach to use this module.



Step 1: Installation and Initialization: Open the terminal and create a node app because at the end we are going to work inside the NodeJS application

npm init 

This command will ask for few configurations about the project and you can fill them easily, otherwise use the -y flag to set default configurations.



 

Now Install the colors module 

npm install colors

Create a javascript file (let’s name it app.js) to write the entire code inside that.

touch app.js

Step 2: Import module in the application: Import the module with require keyword and with this, you are ready to use the colors module.

const colors = require('colors');

Step 3: Start Working with Module:




const colors = require('colors');
  
console.log('Hello, GeeksforGeeks Learner'.red); 
console.log('Hello, GeeksforGeeks Learner'.bgMagenta); 
console.log('Hello, GeeksforGeeks Learner'.bgYellow.blue);

Output:

 




const colors = require('colors');
  
console.log('Hello, GeeksforGeeks Learner'.underline); 
console.log('Hello, GeeksforGeeks Learner'.italic); 
console.log('Hello, GeeksforGeeks Learner'.bold); 
console.log('Hello, GeeksforGeeks Learner'.inverse);

Output:




const colors = require('colors');
colors.setTheme({
    info: 'green',
    data: 'grey',
    help: 'cyan',
    warn: 'yellow',
    debug: ['blue','bold'],
    error: ['red', 'underline', 'bgWhite']
});
  
console.log("This is a debug line".debug);
console.log("This is an error".error);
console.log("This is a warning".warn);

Output:

Additional Points:




const colors = require('colors');
  
colors.disable();
console.log('Colors module is being disabled in this zone'.red); 
colors.enable();
  
console.log('Colors module has been enabled'.rainbow);

Output:

colors.someProperties("Any String")




var colors = require('colors/safe');
   
console.log(colors.green('Hello, GeeksforGeeks Learner'));
console.log(colors.red.underline('Hello, GeeksforGeeks Learner'));
console.log(colors.inverse('Hello, GeeksforGeeks Learner'));

Output:

Conclusion: This was the general introduction to the colors module, and you can explore it more in your own way also you can check out the official docs and repository of the module.


Article Tags :