Node.js: Colorizing console.log() output without third-party libraries
By default, when you print something by using console.log() in Node.js, the output is usually white if your terminal has a dark background color or black if your terminal has a light background color.
If you print a few short messages using console.log(), there will be nothing to worry about. However, when you print some long text, it may become a mess and hard to read.
For example, we’ll create a file called index.js and put into it some code like this:
// red console.log('\x1b[31m', 'I am red') // green console.log('\x1b[32m', 'I am green') // yellow console.log('\x1b[33m', 'I am yellow') // blue console.log('\x1b[34m', 'I am blue') // magenta console.log('\x1b[35m', 'I am magenta') // cyan console.log('\x1b[36m', 'I am cyan')
Execute the code by typing the following command in the terminal window (If using Visual Studio Code, you can open the terminal by pressing ctrl + ~):
An here is the result:
Happy coding 🙂