Node.js provides a powerful way to customize console output using ANSI escape codes, which allow you to change text color, background color, and style. In this tutorial, we’ll explore how to use these codes to create visually appealing and informative console output.
Understanding ANSI Escape Codes
ANSI escape codes are a set of standard codes used by terminals to control the formatting of text. They consist of a sequence of characters that start with the ESC (escape) character (\x1b
) followed by a bracket ([
), a code, and a letter (m
). For example, \x1b[31m
is an escape sequence that sets the text color to red.
Basic Colors
Here are some basic colors you can use in your console output:
- Reset:
\x1b[0m
- Bright:
\x1b[1m
- Dim:
\x1b[2m
- Underscore:
\x1b[4m
- Blink:
\x1b[5m
- Reverse:
\x1b[7m
- Hidden:
\x1b[8m
You can also use the following foreground (text) colors:
- Black:
\x1b[30m
- Red:
\x1b[31m
- Green:
\x1b[32m
- Yellow:
\x1b[33m
- Blue:
\x1b[34m
- Magenta:
\x1b[35m
- Cyan:
\x1b[36m
- White:
\x1b[37m
- Gray:
\x1b[90m
And the following background colors:
- Black:
\x1b[40m
- Red:
\x1b[41m
- Green:
\x1b[42m
- Yellow:
\x1b[43m
- Blue:
\x1b[44m
- Magenta:
\x1b[45m
- Cyan:
\x1b[46m
- White:
\x1b[47m
- Gray:
\x1b[100m
Using ANSI Escape Codes in Node.js
To use ANSI escape codes in Node.js, you can simply include them in your console.log
statements. For example:
console.log('\x1b[36m', 'This text will be cyan', '\x1b[0m');
Note that the \x1b[0m
at the end resets the text color to its default value.
Using Utility Modules
There are several utility modules available that make it easier to work with ANSI escape codes in Node.js. Some popular options include:
node:util
: Provides astyleText
method for styling console output.chalk
: A popular module for coloring and styling console output.picocolors
: A lightweight alternative tochalk
.cli-color
: Another module for coloring and styling console output.
Here’s an example of how you might use the node:util
module:
import { styleText } from 'node:util';
console.log(styleText('green', 'This text will be green'));
And here’s an example of how you might use the chalk
module:
const chalk = require('chalk');
console.log(chalk.red('This text will be red'));
Best Practices
When working with ANSI escape codes, it’s a good idea to keep the following best practices in mind:
- Always reset the text color to its default value after using an ANSI escape code.
- Use utility modules to simplify your code and make it more readable.
- Be mindful of the fact that not all terminals support ANSI escape codes.
By following these best practices and using the techniques outlined in this tutorial, you can create visually appealing and informative console output in Node.js.