Skip to content

Commit

Permalink
util: add styleText API to text formatting
Browse files Browse the repository at this point in the history
Co-Authored-By: Hemanth HM <[email protected]>
PR-URL: #51850
Reviewed-By: Matteo Collina <[email protected]>
Reviewed-By: Adrian Estrada <[email protected]>
Reviewed-By: Marco Ippolito <[email protected]>
Reviewed-By: Antoine du Hamel <[email protected]>
Reviewed-By: Moshe Atlow <[email protected]>
Reviewed-By: Geoffrey Booth <[email protected]>
  • Loading branch information
2 people authored and marco-ippolito committed Feb 27, 2024
1 parent 8dc3f91 commit 88e08bb
Show file tree
Hide file tree
Showing 3 changed files with 88 additions and 0 deletions.
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
`underline` and you can combine both:
```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];
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 @@ -393,6 +408,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');

0 comments on commit 88e08bb

Please sign in to comment.