Skip to content

Commit 01a77c8

Browse files
authored
doc: add colorText
1 parent 7cd400f commit 01a77c8

File tree

1 file changed

+9
-45
lines changed

1 file changed

+9
-45
lines changed

doc/api/util.md

Lines changed: 9 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -16,59 +16,23 @@ const util = require('node:util');
1616

1717
## `util.callbackify(original)`
1818

19+
## `util.colorText(format, text)`
20+
1921
<!-- YAML
20-
added: v8.2.0
22+
added: v18.3.0
2123
-->
2224

23-
* `original` {Function} An `async` function
24-
* Returns: {Function} a callback style function
25+
* `format` {String} `format` one of the color format from `util.inspect.colors`
26+
* `text` {String} The text you would like to color
27+
* Returns: {string} colored text string
2528

26-
Takes an `async` function (or a function that returns a `Promise`) and returns a
27-
function following the error-first callback style, i.e. taking
28-
an `(err, value) => ...` callback as the last argument. In the callback, the
29-
first argument will be the rejection reason (or `null` if the `Promise`
30-
resolved), and the second argument will be the resolved value.
29+
Takes `format` and `text` and retuns the colored text form
3130

3231
```js
3332
const util = require('node:util');
3433

35-
async function fn() {
36-
return 'hello world';
37-
}
38-
const callbackFunction = util.callbackify(fn);
39-
40-
callbackFunction((err, ret) => {
41-
if (err) throw err;
42-
console.log(ret);
43-
});
44-
```
45-
46-
Will print:
47-
48-
```text
49-
hello world
50-
```
51-
52-
The callback is executed asynchronously, and will have a limited stack trace.
53-
If the callback throws, the process will emit an [`'uncaughtException'`][]
54-
event, and if not handled will exit.
55-
56-
Since `null` has a special meaning as the first argument to a callback, if a
57-
wrapped function rejects a `Promise` with a falsy value as a reason, the value
58-
is wrapped in an `Error` with the original value stored in a field named
59-
`reason`.
60-
61-
```js
62-
function fn() {
63-
return Promise.reject(null);
64-
}
65-
const callbackFunction = util.callbackify(fn);
66-
67-
callbackFunction((err, ret) => {
68-
// When the Promise was rejected with `null` it is wrapped with an Error and
69-
// the original value is stored in `reason`.
70-
err && Object.hasOwn(err, 'reason') && err.reason === null; // true
71-
});
34+
console.log(util.colorText('red', 'This text shall be in red color'));
35+
// ^ '\u001b[31mThis text shall be in red color\u001b[39m'
7236
```
7337

7438
## `util.debuglog(section[, callback])`

0 commit comments

Comments
 (0)