Skip to content

Instantly share code, notes, and snippets.

@TheNolle
Last active May 16, 2024 20:58
Show Gist options
  • Save TheNolle/1e8ff2eb6d246780f947964a72937dd5 to your computer and use it in GitHub Desktop.
Save TheNolle/1e8ff2eb6d246780f947964a72937dd5 to your computer and use it in GitHub Desktop.
An extension to the console that allows you to use colors directly in a string

Important

It is for Node.JS only

How to use it ?

Either add the class and the line global.console = new Console() in your main file, or put it in another folder and require/import the file in your main file.
Basically, in your main file you add require('path/to/the/file/console.color').
It will allow you to use the command console.color(<string>) anywhere.
Colors are used the same way as minecraft: &<code>

Example

Code: console.color('&a[&dTest&a] &bThis is an example.')
Result: example.png

// Extend the built-in console class to add custom color method
class Console extends console.Console {
constructor() {
// Call the parent constructor with the default stdout and stderr streams
super(process.stdout, process.stderr)
}
// Add a custom color method to the console class
color(string) {
// Define the color codes and their corresponding ANSI escape codes
const colors = ['&0', '&1', '&2', '&3', '&4', '&5', '&6', '&7', '&8', '&9', '&a', '&b', '&c', '&d', '&e', '&f', '&l', '&n', '&r']
const colors_ = ['30', '94', '32', '36', '31', '35', '33', '37', '90', '34', '92', '96', '91', '95', '93', '97', '1', '4', '0']
// Replace each color code in the input string with its corresponding ANSI escape code
for (var i = 0; i < colors.length; i++) string = string.replaceAll(colors[i], `\u001b[${colors_[i]}m`)
// Log the colored string and reset the console color with '\u001b[0m'
console.log(string + '\u001b[0m')
}
}
// Set the global console object to be an instance of the custom console class
global.console = new Console()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment