File tree Expand file tree Collapse file tree 2 files changed +50
-0
lines changed Expand file tree Collapse file tree 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');
6464const {
6565 validateFunction,
6666 validateNumber,
67+ validateString,
6768} = require ( 'internal/validators' ) ;
6869const { TextDecoder, TextEncoder } = require ( 'internal/encoding' ) ;
6970const { isBuffer } = require ( 'buffer' ) . Buffer ;
@@ -331,12 +332,28 @@ function getSystemErrorName(err) {
331332 return internalErrorName ( err ) ;
332333}
333334
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+
334350// Keep the `exports =` so that various functions can still be monkeypatched
335351module . exports = {
336352 _errnoException : errnoException ,
337353 _exceptionWithHostPort : exceptionWithHostPort ,
338354 _extend,
339355 callbackify,
356+ colorText,
340357 debug : debuglog ,
341358 debuglog,
342359 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