Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

util: add styleText API to text formatting #51850

Merged
merged 1 commit into from
Feb 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
37 changes: 37 additions & 0 deletions doc/api/util.md
Original file line number Diff line number Diff line change
Expand Up @@ -1792,6 +1792,42 @@ console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m'));
// Prints "value"
```

## `util.styleText(format, text)`

> Stability: 1.1 - Active development

<!-- YAML
added: REPLACEME
-->

* `format` {string} A text format defined in `util.inspect.colors`.
* `text` {string} The text to to be formatted.

This function returns a formatted text considering the `format` passed.

```mjs
import { styleText } from 'node:util';
const errorMessage = styleText('red', 'Error! Error!');
console.log(errorMessage);
```

```cjs
const { styleText } = require('node:util');
const errorMessage = styleText('red', 'Error! Error!');
console.log(errorMessage);
```

`util.inspect.colors` also provides text formats such as `italic`, and
RafaelGSS marked this conversation as resolved.
Show resolved Hide resolved
`underline` and you can combine both:
RafaelGSS marked this conversation as resolved.
Show resolved Hide resolved

```cjs
console.log(
util.styleText('underline', util.styleText('italic', 'My italic underlined message')),
);
```

The full list of formats can be found in [modifiers][].

## Class: `util.TextDecoder`

<!-- YAML
Expand Down Expand Up @@ -3395,6 +3431,7 @@ util.log('Timestamped message.');
[default sort]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
[global symbol registry]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/for
[list of deprecated APIS]: deprecations.md#list-of-deprecated-apis
[modifiers]: #modifiers
[realm]: https://tc39.es/ecma262/#realm
[semantically incompatible]: https://github.com/nodejs/node/issues/4179
[util.inspect.custom]: #utilinspectcustom
16 changes: 16 additions & 0 deletions lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ const {
validateFunction,
validateNumber,
validateString,
validateOneOf,
} = require('internal/validators');
const { isBuffer } = require('buffer').Buffer;
const types = require('internal/util/types');
Expand Down Expand Up @@ -197,6 +198,20 @@ function pad(n) {
return StringPrototypePadStart(n.toString(), 2, '0');
}

/**
* @param {string} format
* @param {string} text
* @returns {string}
*/
function styleText(format, text) {
validateString(text, 'text');
const formatCodes = inspect.colors[format];
Copy link
Contributor

@kibertoad kibertoad Mar 6, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does it make sense to do this check on every call? could be done once and cached

nvm, happy path should be pretty fast here, misread the code

if (formatCodes == null) {
validateOneOf(format, 'format', ObjectKeys(inspect.colors));
}
return `\u001b[${formatCodes[0]}m${text}\u001b[${formatCodes[1]}m`;
}

const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];

Expand Down Expand Up @@ -395,6 +410,7 @@ module.exports = {
debuglog,
deprecate,
format,
styleText,
formatWithOptions,
getSystemErrorMap,
getSystemErrorName,
Expand Down
35 changes: 35 additions & 0 deletions test/parallel/test-util-styletext.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
'use strict';
require('../common');
const assert = require('assert');
const util = require('util');

[
undefined,
null,
false,
5n,
5,
Symbol(),
() => {},
{},
[],
].forEach((invalidOption) => {
assert.throws(() => {
util.styleText(invalidOption, 'test');
}, {
code: 'ERR_INVALID_ARG_VALUE',
});
assert.throws(() => {
util.styleText('red', invalidOption);
}, {
code: 'ERR_INVALID_ARG_TYPE'
});
});

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

assert.strictEqual(util.styleText('red', 'test'), '\u001b[31mtest\u001b[39m');