diff --git a/lib/util.js b/lib/util.js index aa54afee9d369f..a810b3b536755d 100644 --- a/lib/util.js +++ b/lib/util.js @@ -123,7 +123,6 @@ function styleText(format, text, { validateStream = true, stream = process.stdou validateString(text, 'text'); validateBoolean(validateStream, 'options.validateStream'); - let skipColorize; if (validateStream) { if ( !isReadableStream(stream) && @@ -134,9 +133,13 @@ function styleText(format, text, { validateStream = true, stream = process.stdou } // If the stream is falsy or should not be colorized, set skipColorize to true - skipColorize = !lazyUtilColors().shouldColorize(stream); + const skipColorize = !lazyUtilColors().shouldColorize(stream); + if (skipColorize) { + return text; + } } + // If the format is not an array, convert it to an array const formatArray = ArrayIsArray(format) ? format : [format]; @@ -148,14 +151,9 @@ function styleText(format, text, { validateStream = true, stream = process.stdou if (formatCodes == null) { validateOneOf(key, 'format', ObjectKeys(inspect.colors)); } - if (skipColorize) continue; ArrayPrototypePush(codes, formatCodes); } - if (skipColorize) { - return text; - } - // Build opening codes let openCodes = ''; for (let i = 0; i < codes.length; i++) { diff --git a/test/parallel/test-util-styletext.js b/test/parallel/test-util-styletext.js index b87c5d7e82c74c..b4735cd0c79ea8 100644 --- a/test/parallel/test-util-styletext.js +++ b/test/parallel/test-util-styletext.js @@ -5,6 +5,8 @@ const assert = require('node:assert'); const util = require('node:util'); const { WriteStream } = require('node:tty'); +process.env.FORCE_COLOR = '1'; + const styled = '\u001b[31mtest\u001b[39m'; const noChange = 'test'; @@ -36,6 +38,14 @@ assert.throws(() => { code: 'ERR_INVALID_ARG_VALUE', }); +assert.throws(() => { + util.styleText(['invalid'], 'text'); +}, { + code: 'ERR_INVALID_ARG_VALUE', +}); + +process.env.FORCE_COLOR = '0'; + assert.strictEqual( util.styleText('red', 'test', { validateStream: false }), '\u001b[31mtest\u001b[39m', @@ -132,12 +142,6 @@ assert.strictEqual( ), ); -assert.throws(() => { - util.styleText(['invalid'], 'text'); -}, { - code: 'ERR_INVALID_ARG_VALUE', -}); - assert.throws(() => { util.styleText('red', 'text', { stream: {} }); }, { @@ -154,6 +158,8 @@ assert.strictEqual( assert.strictEqual(util.styleText('none', 'test'), 'test'); +delete process.env.FORCE_COLOR; + const fd = common.getTTYfd(); if (fd !== -1) { const writeStream = new WriteStream(fd);