diff --git a/lib/util.js b/lib/util.js index b3306a539d9..856b2cb39d5 100644 --- a/lib/util.js +++ b/lib/util.js @@ -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], }; } @@ -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; diff --git a/test/parallel/test-util-styletext.js b/test/parallel/test-util-styletext.js index ba81aae06d8..8080948f216 100644 --- a/test/parallel/test-util-styletext.js +++ b/test/parallel/test-util-styletext.js @@ -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, + ); +}