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
12 changes: 5 additions & 7 deletions lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) &&
Expand All @@ -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];

Expand All @@ -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++) {
Expand Down
18 changes: 12 additions & 6 deletions test/parallel/test-util-styletext.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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',
Expand Down Expand Up @@ -132,12 +142,6 @@ assert.strictEqual(
),
);

assert.throws(() => {
util.styleText(['invalid'], 'text');
}, {
code: 'ERR_INVALID_ARG_VALUE',
});

assert.throws(() => {
util.styleText('red', 'text', { stream: {} });
}, {
Expand All @@ -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);
Expand Down
Loading