Easy Ansi Escape Code in C♯ and Javascript
I've been really rather ill over the weekend, so I wasn't able to write a post when I wanted to. I'm starting to recover now though, so I thought I'd write a quick post about a class I've written in C♯ (and later ported to Javascript via an ES6 Module) that makes using VT100 Ansi escape codes easy.
Such codes are really useful for changing the text colour & background in a terminal or console, and for moving the cursor around to draw fancy UI elements with just text.
I initially wrote it a few months ago as part of an ACW (Assessed CourseWork), but out of an abundance of caution I've held back on open-sourcing this particular code fragment that drove the code I submitted for that assessment.
Now that the assessment is done & marked though (and I've used this class in a few projects since), I feel comfortable with publishing the code I've written publically. Here it is in C♯:
(Can't see the above? Try this direct link instead)
In short, it's a static class that contains a bunch of Ansi escape codes that you can include in strings that you send out via Console.WriteLine()
- no special fiddling required! Though, if you're on Windows, don't forget you need to enable escape sequences first. Here's an example that uses the C♯ class:
// ....
catch(Exception error) {
Console.WriteLine($"{Ansi.FRed}Error: Oops! Something went wrong.");
Console.WriteLine($" {error.Message}{Ansi.Reset}");
return;
}
// ....
Of course, you can get as elaborate as you like. In addition, if you need to disable all escape sequence output for some reason (e.g. you know you're writing to a log file), simply set Ansi.Enabled
to false
.
Some time later, I found myself needing this class in Javascript (for a Node.js application I'm pretty sure) quite badly (reason - I might blog about it soon :P). To that end, I wound up porting it from C♯ to Javascript. The process wasn't actually that painful - probably because it's a fairly small and simple class.
With porting complete, I intend to keep both versions in sync with each other as I add more features - but no promises :P
Here's the Javascript version:
(Can't see the above? Try this direct link instead)
The Javascript version isn't actually a static class as like the C♯ version, due to the way ES6 modules work. In the future, I'd like to do some science and properly figure out the ins and outs of ES6 modules and refactor this into the JS equivalent of a globally static class (or a Singleton, though in JS we don't have to worry about thread safety 'cause the only way to communicate between threads (also) in JS is through messaging).
Still, it works well enough for my purposes for now.
Found this interesting? Got an improvement? Just want to say hi? Comment below!