Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,8 @@ function codesToStyle(codes) {
openSeq: kEscape + openNum + kEscapeEnd,
closeSeq: kEscape + codes[1] + kEscapeEnd,
keepClose: openNum === kDimCode || openNum === kBoldCode,
openCode: openNum,
closeCode: codes[1],
};
}

Expand Down Expand Up @@ -251,7 +253,21 @@ function styleText(format, text, options) {
if (!validateStream && typeof format === 'string' && typeof text === 'string') {
const cache = getStyleCache();
if (format === 'none') return text;
const style = cache[format];
let style = cache[format];
// util.inspect.colors can be customized after the first call, so
// refresh the cached entry when the live codes changed.
const codes = inspect.colors[format];
if (codes !== undefined) {
if (style === undefined ||
style.openCode !== codes[0] || style.closeCode !== codes[1]) {
style = cache[format] = codesToStyle(codes);
}
} else if (style !== undefined) {
// The color was removed, drop the stale entry and fall through
// to the slow path, which throws ERR_INVALID_ARG_VALUE.
delete cache[format];
style = undefined;
}
if (style !== undefined) {
const processed = replaceCloseCode(text, style.closeSeq, style.openSeq, style.keepClose);
return style.openSeq + processed + style.closeSeq;
Expand Down
17 changes: 17 additions & 0 deletions test/parallel/test-util-styletext.js
Original file line number Diff line number Diff line change
Expand Up @@ -223,3 +223,20 @@ if (fd !== -1) {
} else {
common.skip('Could not create TTY fd');
}

// https://github.com/nodejs/node/issues/67980
// The styleText() fast path must pick up changes to util.inspect.colors.
{
const originalRed = util.inspect.colors.red;
util.styleText('red', 'test', { validateStream: false });
util.inspect.colors.red = [91, 39];
assert.strictEqual(
util.styleText('red', 'test', { validateStream: false }),
'\u001b[91mtest\u001b[39m',
);
util.inspect.colors.red = originalRed;
assert.strictEqual(
util.styleText('red', 'test', { validateStream: false }),
styled,
);
}
Loading