Mazzarolo Matteo
Mazzarolo Matteo

Simple colored logging for your JavaScript CLI output

By Mazzarolo Matteo


I love writing CLI scripts using JavaScript (mostly with deno, zx, or plain node.js).

Here’s something I add to almost all my scripts: a tiny copy-pasteable way to color the output of success and failure messages without adding external libraries.

With a green and a red character:

console.success = (...args) => console.log("\x1b[32m✔\x1b[0m", ...args);
console.failure = (...args) => console.error("\x1b[31mx\x1b[0m", ...args);

console.success("Files copied successfully");
console.failure("Unable to delete the 'system32' directory");

symbols

With the green success and a red failure prefix:

console.success = (...args) => console.log("\x1b[32msuccess\x1b[0m", ...args);
console.failure = (...args) => console.error("\x1b[31mfailure\x1b[0m", ...args);

console.success("Files copied successfully");
console.failure("Unable to delete the 'system32' directory");

prefixes

And that’s it — no need for chalk and friends.

By the way, generally I don’t promote extending global APIs such as console. But for tiny scripts, it’s too handy: just copy-paste these two lines at the top of your file, and you’re set.
If you really can’t stand overriding global variables, you can use composition instead:

const logger = {
  ...console,
  success: (...args) => console.log("\x1b[32msuccess\x1b[0m", ...args),
  failure: (...args) => console.error("\x1b[31mfailure\x1b[0m", ...args),
};

logger.success("Files copied successfully");
logger.failure("Unable to delete the 'system32' directory");

For more details around the color escaping sequences, check out “How to change node.js’s console font color?” on StackOverflow.