From ead727c274a5545af70bbca6b1b887c7055660fe Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Tue, 16 Jan 2018 13:20:13 +0100 Subject: [PATCH] tty: add getColorDepth function Right now it is very difficult to determine if a terminal supports colors or not. This function adds this functionality by detecting environment variables and checking process. Backport-PR-URL: https://github.com/nodejs/node/pull/19230 PR-URL: https://github.com/nodejs/node/pull/17615 Reviewed-By: James M Snell Reviewed-By: Matteo Collina --- doc/api/assert.md | 3 + doc/api/tty.md | 26 ++++++++ lib/internal/errors.js | 21 +++++-- lib/tty.js | 72 +++++++++++++++++++++++ test/parallel/test-assert.js | 9 ++- test/parallel/test-tty-get-color-depth.js | 52 ++++++++++++++++ 6 files changed, 175 insertions(+), 8 deletions(-) create mode 100644 test/parallel/test-tty-get-color-depth.js diff --git a/doc/api/assert.md b/doc/api/assert.md index 68b01350dfdee6..0698f54c23404f 100644 --- a/doc/api/assert.md +++ b/doc/api/assert.md @@ -65,6 +65,9 @@ AssertionError [ERR_ASSERTION]: Input A expected to deepStrictEqual input B: ] ``` +To deactivate the colors, use the `NODE_DISABLE_COLORS` environment variable. +Please note that this will also deactivate the colors in the REPL. + ## Legacy mode > Stability: 0 - Deprecated: Use strict mode instead. diff --git a/doc/api/tty.md b/doc/api/tty.md index 8b757c0f02751a..ce6dbae8fa6e7d 100644 --- a/doc/api/tty.md +++ b/doc/api/tty.md @@ -121,6 +121,32 @@ added: v0.7.7 A `number` specifying the number of rows the TTY currently has. This property is updated whenever the `'resize'` event is emitted. +### writeStream.getColorDepth([env]) + + +* `env` {object} A object containing the environment variables to check. + Defaults to `process.env`. +* Returns: {number} + +Returns: +* 1 for 2, +* 4 for 16, +* 8 for 256, +* 24 for 16,777,216 +colors supported. + +Use this to determine what colors the terminal supports. Due to the nature of +colors in terminals it is possible to either have false positives or false +negatives. It depends on process information and the environment variables that +may lie about what terminal is used. +To enforce a specific behavior without relying on `process.env` it is possible +to pass in an object with different settings. + +Use the `NODE_DISABLE_COLORS` environment variable to enforce this function to +always return 1. + ## tty.isatty(fd)