util: add 'none' style to styleText

For cases where the style is not needed but code still calls styleText
unconditionally, this adds a `none` style that not not apply any styling
to the text.

PR-URL: https://github.com/nodejs/node/pull/58437
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
This commit is contained in:
James M Snell 2025-05-23 09:07:10 -07:00 committed by Antoine du Hamel
parent 20d978de9a
commit 54288bdb42
No known key found for this signature in database
GPG Key ID: 21D900FFDB233756
3 changed files with 10 additions and 1 deletions

View File

@ -2394,6 +2394,9 @@ added:
- v21.7.0 - v21.7.0
- v20.12.0 - v20.12.0
changes: changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/58437
description: Added the `'none'` format as a non-op format.
- version: v22.13.0 - version: v22.13.0
pr-url: https://github.com/nodejs/node/pull/56265 pr-url: https://github.com/nodejs/node/pull/56265
description: styleText is now stable. description: styleText is now stable.
@ -2467,6 +2470,8 @@ console.log(
); );
``` ```
The special format value `none` applies no additional styling to the text.
The full list of formats can be found in [modifiers][]. The full list of formats can be found in [modifiers][].
## Class: `util.TextDecoder` ## Class: `util.TextDecoder`

View File

@ -217,10 +217,11 @@ function pad(n) {
} }
/** /**
* @param {string} code * @param {string} [code]
* @returns {string} * @returns {string}
*/ */
function escapeStyleCode(code) { function escapeStyleCode(code) {
if (code === undefined) return '';
return `\u001b[${code}m`; return `\u001b[${code}m`;
} }
@ -256,6 +257,7 @@ function styleText(format, text, { validateStream = true, stream = process.stdou
let left = ''; let left = '';
let right = ''; let right = '';
for (const key of formatArray) { for (const key of formatArray) {
if (key === 'none') continue;
const formatCodes = inspect.colors[key]; const formatCodes = inspect.colors[key];
// If the format is not a valid style, throw an error // If the format is not a valid style, throw an error
if (formatCodes == null) { if (formatCodes == null) {

View File

@ -75,6 +75,8 @@ assert.strictEqual(
styled, styled,
); );
assert.strictEqual(util.styleText('none', 'test'), 'test');
const fd = common.getTTYfd(); const fd = common.getTTYfd();
if (fd !== -1) { if (fd !== -1) {
const writeStream = new WriteStream(fd); const writeStream = new WriteStream(fd);