File tree 2 files changed +50
-0
lines changed
2 files changed +50
-0
lines changed Original file line number Diff line number Diff line change @@ -64,6 +64,7 @@ const { debuglog } = require('internal/util/debuglog');
64
64
const {
65
65
validateFunction,
66
66
validateNumber,
67
+ validateString,
67
68
} = require ( 'internal/validators' ) ;
68
69
const { TextDecoder, TextEncoder } = require ( 'internal/encoding' ) ;
69
70
const { isBuffer } = require ( 'buffer' ) . Buffer ;
@@ -331,12 +332,28 @@ function getSystemErrorName(err) {
331
332
return internalErrorName ( err ) ;
332
333
}
333
334
335
+ /**
336
+ * @param {string } format
337
+ * @param {string } text
338
+ * @returns {string }
339
+ */
340
+ function colorText ( format , text ) {
341
+ validateString ( format , 'format' ) ;
342
+ validateString ( text , 'text' ) ;
343
+ const formatCodes = inspect . colors [ format ] ;
344
+ if ( ! ArrayIsArray ( formatCodes ) ) {
345
+ return text ;
346
+ }
347
+ return `\u001b[${ formatCodes [ 0 ] } m${ text } \u001b[${ formatCodes [ 1 ] } m` ;
348
+ }
349
+
334
350
// Keep the `exports =` so that various functions can still be monkeypatched
335
351
module . exports = {
336
352
_errnoException : errnoException ,
337
353
_exceptionWithHostPort : exceptionWithHostPort ,
338
354
_extend,
339
355
callbackify,
356
+ colorText,
340
357
debug : debuglog ,
341
358
debuglog,
342
359
deprecate,
Original file line number Diff line number Diff line change
1
+ 'use strict' ;
2
+ require ( '../common' ) ;
3
+ const assert = require ( 'assert' ) ;
4
+ const util = require ( 'util' ) ;
5
+
6
+ [
7
+ undefined ,
8
+ null ,
9
+ false ,
10
+ 5n ,
11
+ 5 ,
12
+ Symbol ( ) ,
13
+ ] . forEach ( ( invalidOption ) => {
14
+ assert . throws ( ( ) => {
15
+ util . colorText ( invalidOption , 'test' ) ;
16
+ } , {
17
+ code : 'ERR_INVALID_ARG_TYPE'
18
+ } ) ;
19
+ assert . throws ( ( ) => {
20
+ util . colorText ( 'red' , invalidOption ) ;
21
+ } , {
22
+ code : 'ERR_INVALID_ARG_TYPE'
23
+ } ) ;
24
+ } ) ;
25
+
26
+ assert . throws ( ( ) => {
27
+ util . colorText ( 'red' , undefined ) ;
28
+ } , {
29
+ code : 'ERR_INVALID_ARG_TYPE' ,
30
+ message : 'The "text" argument must be of type string. Received undefined'
31
+ } ) ;
32
+
33
+ assert . equal ( util . colorText ( 'red' , 'test' ) , '\u001b[31mtest\u001b[39m' ) ;
You can’t perform that action at this time.
0 commit comments