javascriptnode.jsloggingcolors

NodeJS/JS - write colored text into file


I was wondering if it is possible to append text to a file (e.g. with writeStream) that is colored. There was a lot of information about how to color console.log text, but I wasn't able to find anything about colored text written into a file.

I've tried to use modules like colors or chalk and also adding nodejs color references (e.g. FgBlack = "\x1b[30m"), but always with the fs.createWriteStream() and no result.


Solution

  • Standard text files contain no colour information and don't really have any mechanism to include any.

    (Quick side trip to the world of ...but technically: You can combine some characters (such as waving hand: 👋) with a modifier (such as light skin tone: 🏻) to give a combined glyph (👋🏻) but that's not what you're looking for.)

    There are data formats which are made up of plain text, such as RTF

    {\rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}\f0\pard
    This is some {\b bold} text.\par
    }
    

    or HTML

    <!DOCTYPE html>
    <meta charset="utf-8">
    <title>Example document</title>
    <style>:root { font-family: "Swiss Helvetica"; } strong { font-weight: bold }</style>
    <p>This is some <strong>bold</strong> text</p>
    

    and you could probably throw in the control codes that are output by chalk and recognised by your terminal into that category.

    However, at that point your text file generally won't be refered to as a text file. It will be RTF, HTML or whatever and you'll need to read it with software that can interpret that data format.


    You tagged this question . You might want to look at Colorize Monitoring of Logs, a question on one of Stackoverflow's sister sites about tools which can colourize logs.

    You can keep your log files in plain text and then add colour when you view them.