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 <[email protected]>

PR-URL: #33797
Reviewed-By: Anna Henningsen <[email protected]>
Reviewed-By: Luigi Pinca <[email protected]>
Reviewed-By: Michaël Zasso <[email protected]>
Reviewed-By: James M Snell <[email protected]>
Reviewed-By: Evan Lucas <[email protected]>
Reviewed-By: Yongsheng Zhang <[email protected]>
Reviewed-By: Trivikram Kamat <[email protected]>
  • Loading branch information
BridgeAR authored and codebytere committed Jul 10, 2020
1 parent c8c2885 commit 1c24d86
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 @@ -473,7 +473,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 @@ -2240,6 +2240,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 1c24d86

Please sign in to comment.