Skip to content

Commit

Permalink
util: gracefully handle unknown colors
Browse files Browse the repository at this point in the history
This makes sure colors that are unknown won't cause an error. This
is especially important in case a library wants to use colors
defined by Node.js core, if available and fall back to the default
otherwise.

Signed-off-by: Ruben Bridgewater <ruben@bridgewater.de>

PR-URL: #33797
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Michaël Zasso <targos@protonmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Evan Lucas <evanlucas@me.com>
Reviewed-By: Yongsheng Zhang <zyszys98@gmail.com>
Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
  • Loading branch information
BridgeAR authored and codebytere committed Jun 27, 2020
1 parent 4715a41 commit e3d53f9
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 1 deletion.
3 changes: 2 additions & 1 deletion lib/internal/util/inspect.js
Original file line number Diff line number Diff line change
Expand Up @@ -478,7 +478,8 @@ function stylizeWithColor(str, styleType) {
const style = inspect.styles[styleType];
if (style !== undefined) {
const color = inspect.colors[style];
return `\u001b[${color[0]}m${str}\u001b[${color[1]}m`;
if (color !== undefined)
return `\u001b[${color[0]}m${str}\u001b[${color[1]}m`;
}
return str;
}
Expand Down
6 changes: 6 additions & 0 deletions test/parallel/test-util-inspect.js
Original file line number Diff line number Diff line change
Expand Up @@ -2245,6 +2245,12 @@ assert.strictEqual(
assert.deepStrictEqual(inspect.colors[bgColor], [40 + i, 49]);
assert.deepStrictEqual(inspect.colors[`${bgColor}Bright`], [100 + i, 49]);
});

// Unknown colors are handled gracefully:
const stringStyle = inspect.styles.string;
inspect.styles.string = 'UNKNOWN';
assert.strictEqual(inspect('foobar', { colors: true }), "'foobar'");
inspect.styles.string = stringStyle;
}

assert.strictEqual(
Expand Down

0 comments on commit e3d53f9

Please sign in to comment.