1# Util 2 3<!--introduced_in=v0.10.0--> 4 5> Stability: 2 - Stable 6 7<!-- source_link=lib/util.js --> 8 9The `util` module supports the needs of Node.js internal APIs. Many of the 10utilities are useful for application and module developers as well. To access 11it: 12 13```js 14const util = require('util'); 15``` 16 17## `util.callbackify(original)` 18<!-- YAML 19added: v8.2.0 20--> 21 22* `original` {Function} An `async` function 23* Returns: {Function} a callback style function 24 25Takes an `async` function (or a function that returns a `Promise`) and returns a 26function following the error-first callback style, i.e. taking 27an `(err, value) => ...` callback as the last argument. In the callback, the 28first argument will be the rejection reason (or `null` if the `Promise` 29resolved), and the second argument will be the resolved value. 30 31```js 32const util = require('util'); 33 34async function fn() { 35 return 'hello world'; 36} 37const callbackFunction = util.callbackify(fn); 38 39callbackFunction((err, ret) => { 40 if (err) throw err; 41 console.log(ret); 42}); 43``` 44 45Will print: 46 47```text 48hello world 49``` 50 51The callback is executed asynchronously, and will have a limited stack trace. 52If the callback throws, the process will emit an [`'uncaughtException'`][] 53event, and if not handled will exit. 54 55Since `null` has a special meaning as the first argument to a callback, if a 56wrapped function rejects a `Promise` with a falsy value as a reason, the value 57is wrapped in an `Error` with the original value stored in a field named 58`reason`. 59 60```js 61function fn() { 62 return Promise.reject(null); 63} 64const callbackFunction = util.callbackify(fn); 65 66callbackFunction((err, ret) => { 67 // When the Promise was rejected with `null` it is wrapped with an Error and 68 // the original value is stored in `reason`. 69 err && err.hasOwnProperty('reason') && err.reason === null; // true 70}); 71``` 72 73## `util.debuglog(section[, callback])` 74<!-- YAML 75added: v0.11.3 76--> 77 78* `section` {string} A string identifying the portion of the application for 79 which the `debuglog` function is being created. 80* `callback` {Function} A callback invoked the first time the logging function 81is called with a function argument that is a more optimized logging function. 82* Returns: {Function} The logging function 83 84The `util.debuglog()` method is used to create a function that conditionally 85writes debug messages to `stderr` based on the existence of the `NODE_DEBUG` 86environment variable. If the `section` name appears within the value of that 87environment variable, then the returned function operates similar to 88[`console.error()`][]. If not, then the returned function is a no-op. 89 90```js 91const util = require('util'); 92const debuglog = util.debuglog('foo'); 93 94debuglog('hello from foo [%d]', 123); 95``` 96 97If this program is run with `NODE_DEBUG=foo` in the environment, then 98it will output something like: 99 100```console 101FOO 3245: hello from foo [123] 102``` 103 104where `3245` is the process id. If it is not run with that 105environment variable set, then it will not print anything. 106 107The `section` supports wildcard also: 108 109```js 110const util = require('util'); 111const debuglog = util.debuglog('foo-bar'); 112 113debuglog('hi there, it\'s foo-bar [%d]', 2333); 114``` 115 116if it is run with `NODE_DEBUG=foo*` in the environment, then it will output 117something like: 118 119```console 120FOO-BAR 3257: hi there, it's foo-bar [2333] 121``` 122 123Multiple comma-separated `section` names may be specified in the `NODE_DEBUG` 124environment variable: `NODE_DEBUG=fs,net,tls`. 125 126The optional `callback` argument can be used to replace the logging function 127with a different function that doesn't have any initialization or 128unnecessary wrapping. 129 130```js 131const util = require('util'); 132let debuglog = util.debuglog('internals', (debug) => { 133 // Replace with a logging function that optimizes out 134 // testing if the section is enabled 135 debuglog = debug; 136}); 137``` 138 139## `util.deprecate(fn, msg[, code])` 140<!-- YAML 141added: v0.8.0 142changes: 143 - version: v10.0.0 144 pr-url: https://github.com/nodejs/node/pull/16393 145 description: Deprecation warnings are only emitted once for each code. 146--> 147 148* `fn` {Function} The function that is being deprecated. 149* `msg` {string} A warning message to display when the deprecated function is 150 invoked. 151* `code` {string} A deprecation code. See the [list of deprecated APIs][] for a 152 list of codes. 153* Returns: {Function} The deprecated function wrapped to emit a warning. 154 155The `util.deprecate()` method wraps `fn` (which may be a function or class) in 156such a way that it is marked as deprecated. 157 158```js 159const util = require('util'); 160 161exports.obsoleteFunction = util.deprecate(() => { 162 // Do something here. 163}, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.'); 164``` 165 166When called, `util.deprecate()` will return a function that will emit a 167`DeprecationWarning` using the [`'warning'`][] event. The warning will 168be emitted and printed to `stderr` the first time the returned function is 169called. After the warning is emitted, the wrapped function is called without 170emitting a warning. 171 172If the same optional `code` is supplied in multiple calls to `util.deprecate()`, 173the warning will be emitted only once for that `code`. 174 175```js 176const util = require('util'); 177 178const fn1 = util.deprecate(someFunction, someMessage, 'DEP0001'); 179const fn2 = util.deprecate(someOtherFunction, someOtherMessage, 'DEP0001'); 180fn1(); // Emits a deprecation warning with code DEP0001 181fn2(); // Does not emit a deprecation warning because it has the same code 182``` 183 184If either the `--no-deprecation` or `--no-warnings` command line flags are 185used, or if the `process.noDeprecation` property is set to `true` *prior* to 186the first deprecation warning, the `util.deprecate()` method does nothing. 187 188If the `--trace-deprecation` or `--trace-warnings` command line flags are set, 189or the `process.traceDeprecation` property is set to `true`, a warning and a 190stack trace are printed to `stderr` the first time the deprecated function is 191called. 192 193If the `--throw-deprecation` command line flag is set, or the 194`process.throwDeprecation` property is set to `true`, then an exception will be 195thrown when the deprecated function is called. 196 197The `--throw-deprecation` command line flag and `process.throwDeprecation` 198property take precedence over `--trace-deprecation` and 199`process.traceDeprecation`. 200 201## `util.format(format[, ...args])` 202<!-- YAML 203added: v0.5.3 204changes: 205 - version: v12.11.0 206 pr-url: https://github.com/nodejs/node/pull/29606 207 description: The `%c` specifier is ignored now. 208 - version: v11.4.0 209 pr-url: https://github.com/nodejs/node/pull/23708 210 description: The `%d`, `%f` and `%i` specifiers now support Symbols 211 properly. 212 - version: v12.0.0 213 pr-url: https://github.com/nodejs/node/pull/23162 214 description: The `format` argument is now only taken as such if it actually 215 contains format specifiers. 216 - version: v12.0.0 217 pr-url: https://github.com/nodejs/node/pull/23162 218 description: If the `format` argument is not a format string, the output 219 string's formatting is no longer dependent on the type of the 220 first argument. This change removes previously present quotes 221 from strings that were being output when the first argument 222 was not a string. 223 - version: v11.4.0 224 pr-url: https://github.com/nodejs/node/pull/24806 225 description: The `%o` specifier's `depth` has default depth of 4 again. 226 - version: v11.0.0 227 pr-url: https://github.com/nodejs/node/pull/17907 228 description: The `%o` specifier's `depth` option will now fall back to the 229 default depth. 230 - version: v10.12.0 231 pr-url: https://github.com/nodejs/node/pull/22097 232 description: The `%d` and `%i` specifiers now support BigInt. 233 - version: v8.4.0 234 pr-url: https://github.com/nodejs/node/pull/14558 235 description: The `%o` and `%O` specifiers are supported now. 236--> 237 238* `format` {string} A `printf`-like format string. 239 240The `util.format()` method returns a formatted string using the first argument 241as a `printf`-like format string which can contain zero or more format 242specifiers. Each specifier is replaced with the converted value from the 243corresponding argument. Supported specifiers are: 244 245* `%s`: `String` will be used to convert all values except `BigInt`, `Object` 246 and `-0`. `BigInt` values will be represented with an `n` and Objects that 247 have no user defined `toString` function are inspected using `util.inspect()` 248 with options `{ depth: 0, colors: false, compact: 3 }`. 249* `%d`: `Number` will be used to convert all values except `BigInt` and 250 `Symbol`. 251* `%i`: `parseInt(value, 10)` is used for all values except `BigInt` and 252 `Symbol`. 253* `%f`: `parseFloat(value)` is used for all values expect `Symbol`. 254* `%j`: JSON. Replaced with the string `'[Circular]'` if the argument contains 255 circular references. 256* `%o`: `Object`. A string representation of an object with generic JavaScript 257 object formatting. Similar to `util.inspect()` with options 258 `{ showHidden: true, showProxy: true }`. This will show the full object 259 including non-enumerable properties and proxies. 260* `%O`: `Object`. A string representation of an object with generic JavaScript 261 object formatting. Similar to `util.inspect()` without options. This will show 262 the full object not including non-enumerable properties and proxies. 263* `%c`: `CSS`. This specifier is ignored and will skip any CSS passed in. 264* `%%`: single percent sign (`'%'`). This does not consume an argument. 265* Returns: {string} The formatted string 266 267If a specifier does not have a corresponding argument, it is not replaced: 268 269```js 270util.format('%s:%s', 'foo'); 271// Returns: 'foo:%s' 272``` 273 274Values that are not part of the format string are formatted using 275`util.inspect()` if their type is not `string`. 276 277If there are more arguments passed to the `util.format()` method than the 278number of specifiers, the extra arguments are concatenated to the returned 279string, separated by spaces: 280 281```js 282util.format('%s:%s', 'foo', 'bar', 'baz'); 283// Returns: 'foo:bar baz' 284``` 285 286If the first argument does not contain a valid format specifier, `util.format()` 287returns a string that is the concatenation of all arguments separated by spaces: 288 289```js 290util.format(1, 2, 3); 291// Returns: '1 2 3' 292``` 293 294If only one argument is passed to `util.format()`, it is returned as it is 295without any formatting: 296 297```js 298util.format('%% %s'); 299// Returns: '%% %s' 300``` 301 302`util.format()` is a synchronous method that is intended as a debugging tool. 303Some input values can have a significant performance overhead that can block the 304event loop. Use this function with care and never in a hot code path. 305 306## `util.formatWithOptions(inspectOptions, format[, ...args])` 307<!-- YAML 308added: v10.0.0 309--> 310 311* `inspectOptions` {Object} 312* `format` {string} 313 314This function is identical to [`util.format()`][], except in that it takes 315an `inspectOptions` argument which specifies options that are passed along to 316[`util.inspect()`][]. 317 318```js 319util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 }); 320// Returns 'See object { foo: 42 }', where `42` is colored as a number 321// when printed to a terminal. 322``` 323 324## `util.getSystemErrorName(err)` 325<!-- YAML 326added: v9.7.0 327--> 328 329* `err` {number} 330* Returns: {string} 331 332Returns the string name for a numeric error code that comes from a Node.js API. 333The mapping between error codes and error names is platform-dependent. 334See [Common System Errors][] for the names of common errors. 335 336```js 337fs.access('file/that/does/not/exist', (err) => { 338 const name = util.getSystemErrorName(err.errno); 339 console.error(name); // ENOENT 340}); 341``` 342 343## `util.inherits(constructor, superConstructor)` 344<!-- YAML 345added: v0.3.0 346changes: 347 - version: v5.0.0 348 pr-url: https://github.com/nodejs/node/pull/3455 349 description: The `constructor` parameter can refer to an ES6 class now. 350--> 351 352* `constructor` {Function} 353* `superConstructor` {Function} 354 355Usage of `util.inherits()` is discouraged. Please use the ES6 `class` and 356`extends` keywords to get language level inheritance support. Also note 357that the two styles are [semantically incompatible][]. 358 359Inherit the prototype methods from one [constructor][] into another. The 360prototype of `constructor` will be set to a new object created from 361`superConstructor`. 362 363This mainly adds some input validation on top of 364`Object.setPrototypeOf(constructor.prototype, superConstructor.prototype)`. 365As an additional convenience, `superConstructor` will be accessible 366through the `constructor.super_` property. 367 368```js 369const util = require('util'); 370const EventEmitter = require('events'); 371 372function MyStream() { 373 EventEmitter.call(this); 374} 375 376util.inherits(MyStream, EventEmitter); 377 378MyStream.prototype.write = function(data) { 379 this.emit('data', data); 380}; 381 382const stream = new MyStream(); 383 384console.log(stream instanceof EventEmitter); // true 385console.log(MyStream.super_ === EventEmitter); // true 386 387stream.on('data', (data) => { 388 console.log(`Received data: "${data}"`); 389}); 390stream.write('It works!'); // Received data: "It works!" 391``` 392 393ES6 example using `class` and `extends`: 394 395```js 396const EventEmitter = require('events'); 397 398class MyStream extends EventEmitter { 399 write(data) { 400 this.emit('data', data); 401 } 402} 403 404const stream = new MyStream(); 405 406stream.on('data', (data) => { 407 console.log(`Received data: "${data}"`); 408}); 409stream.write('With ES6'); 410``` 411 412## `util.inspect(object[, options])` 413## `util.inspect(object[, showHidden[, depth[, colors]]])` 414<!-- YAML 415added: v0.3.0 416changes: 417 - version: 418 - v14.6.0 419 - v12.19.0 420 pr-url: https://github.com/nodejs/node/pull/33690 421 description: If `object` is from a different `vm.Context` now, a custom 422 inspection function on it will not receive context-specific 423 arguments anymore. 424 - version: v12.17.0 425 pr-url: https://github.com/nodejs/node/pull/32392 426 description: The `maxStringLength` option is supported now. 427 - version: v12.16.0 428 pr-url: https://github.com/nodejs/node/pull/30768 429 description: User defined prototype properties are inspected in case 430 `showHidden` is `true`. 431 - version: v12.0.0 432 pr-url: https://github.com/nodejs/node/pull/27109 433 description: The `compact` options default is changed to `3` and the 434 `breakLength` options default is changed to `80`. 435 - version: v11.11.0 436 pr-url: https://github.com/nodejs/node/pull/26269 437 description: The `compact` option accepts numbers for a new output mode. 438 - version: v12.0.0 439 pr-url: https://github.com/nodejs/node/pull/24971 440 description: Internal properties no longer appear in the context argument 441 of a custom inspection function. 442 - version: v11.7.0 443 pr-url: https://github.com/nodejs/node/pull/25006 444 description: ArrayBuffers now also show their binary contents. 445 - version: v11.5.0 446 pr-url: https://github.com/nodejs/node/pull/24852 447 description: The `getters` option is supported now. 448 - version: v11.4.0 449 pr-url: https://github.com/nodejs/node/pull/24326 450 description: The `depth` default changed back to `2`. 451 - version: v11.0.0 452 pr-url: https://github.com/nodejs/node/pull/22846 453 description: The `depth` default changed to `20`. 454 - version: v10.12.0 455 pr-url: https://github.com/nodejs/node/pull/22788 456 description: The `sorted` option is supported now. 457 - version: v11.0.0 458 pr-url: https://github.com/nodejs/node/pull/22756 459 description: The inspection output is now limited to about 128 MB. Data 460 above that size will not be fully inspected. 461 - version: v10.6.0 462 pr-url: https://github.com/nodejs/node/pull/20725 463 description: Inspecting linked lists and similar objects is now possible 464 up to the maximum call stack size. 465 - version: v10.0.0 466 pr-url: https://github.com/nodejs/node/pull/19259 467 description: The `WeakMap` and `WeakSet` entries can now be inspected 468 as well. 469 - version: v9.9.0 470 pr-url: https://github.com/nodejs/node/pull/17576 471 description: The `compact` option is supported now. 472 - version: v6.6.0 473 pr-url: https://github.com/nodejs/node/pull/8174 474 description: Custom inspection functions can now return `this`. 475 - version: v6.3.0 476 pr-url: https://github.com/nodejs/node/pull/7499 477 description: The `breakLength` option is supported now. 478 - version: v6.1.0 479 pr-url: https://github.com/nodejs/node/pull/6334 480 description: The `maxArrayLength` option is supported now; in particular, 481 long arrays are truncated by default. 482 - version: v6.1.0 483 pr-url: https://github.com/nodejs/node/pull/6465 484 description: The `showProxy` option is supported now. 485--> 486 487* `object` {any} Any JavaScript primitive or `Object`. 488* `options` {Object} 489 * `showHidden` {boolean} If `true`, `object`'s non-enumerable symbols and 490 properties are included in the formatted result. [`WeakMap`][] and 491 [`WeakSet`][] entries are also included as well as user defined prototype 492 properties (excluding method properties). **Default:** `false`. 493 * `depth` {number} Specifies the number of times to recurse while formatting 494 `object`. This is useful for inspecting large objects. To recurse up to 495 the maximum call stack size pass `Infinity` or `null`. 496 **Default:** `2`. 497 * `colors` {boolean} If `true`, the output is styled with ANSI color 498 codes. Colors are customizable. See [Customizing `util.inspect` colors][]. 499 **Default:** `false`. 500 * `customInspect` {boolean} If `false`, 501 `[util.inspect.custom](depth, opts)` functions are not invoked. 502 **Default:** `true`. 503 * `showProxy` {boolean} If `true`, `Proxy` inspection includes 504 the [`target` and `handler`][] objects. **Default:** `false`. 505 * `maxArrayLength` {integer} Specifies the maximum number of `Array`, 506 [`TypedArray`][], [`WeakMap`][] and [`WeakSet`][] elements to include when 507 formatting. Set to `null` or `Infinity` to show all elements. Set to `0` or 508 negative to show no elements. **Default:** `100`. 509 * `maxStringLength` {integer} Specifies the maximum number of characters to 510 include when formatting. Set to `null` or `Infinity` to show all elements. 511 Set to `0` or negative to show no characters. **Default:** `Infinity`. 512 * `breakLength` {integer} The length at which input values are split across 513 multiple lines. Set to `Infinity` to format the input as a single line 514 (in combination with `compact` set to `true` or any number >= `1`). 515 **Default:** `80`. 516 * `compact` {boolean|integer} Setting this to `false` causes each object key 517 to be displayed on a new line. It will also add new lines to text that is 518 longer than `breakLength`. If set to a number, the most `n` inner elements 519 are united on a single line as long as all properties fit into 520 `breakLength`. Short array elements are also grouped together. No 521 text will be reduced below 16 characters, no matter the `breakLength` size. 522 For more information, see the example below. **Default:** `3`. 523 * `sorted` {boolean|Function} If set to `true` or a function, all properties 524 of an object, and `Set` and `Map` entries are sorted in the resulting 525 string. If set to `true` the [default sort][] is used. If set to a function, 526 it is used as a [compare function][]. 527 * `getters` {boolean|string} If set to `true`, getters are inspected. If set 528 to `'get'`, only getters without a corresponding setter are inspected. If 529 set to `'set'`, only getters with a corresponding setter are inspected. 530 This might cause side effects depending on the getter function. 531 **Default:** `false`. 532* Returns: {string} The representation of `object`. 533 534The `util.inspect()` method returns a string representation of `object` that is 535intended for debugging. The output of `util.inspect` may change at any time 536and should not be depended upon programmatically. Additional `options` may be 537passed that alter the result. 538`util.inspect()` will use the constructor's name and/or `@@toStringTag` to make 539an identifiable tag for an inspected value. 540 541```js 542class Foo { 543 get [Symbol.toStringTag]() { 544 return 'bar'; 545 } 546} 547 548class Bar {} 549 550const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } }); 551 552util.inspect(new Foo()); // 'Foo [bar] {}' 553util.inspect(new Bar()); // 'Bar {}' 554util.inspect(baz); // '[foo] {}' 555``` 556 557Circular references are marked as `'[Circular]'`: 558 559```js 560const { inspect } = require('util'); 561 562const obj = {}; 563obj.a = [obj]; 564obj.b = {}; 565obj.b.inner = obj.b; 566obj.b.obj = obj; 567 568console.log(inspect(obj)); 569// { 570// a: [ [Circular] ], 571// b: { inner: [Circular], obj: [Circular] } 572// } 573``` 574 575The following example inspects all properties of the `util` object: 576 577```js 578const util = require('util'); 579 580console.log(util.inspect(util, { showHidden: true, depth: null })); 581``` 582 583The following example highlights the effect of the `compact` option: 584 585```js 586const util = require('util'); 587 588const o = { 589 a: [1, 2, [[ 590 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do ' + 591 'eiusmod tempor incididunt ut labore et dolore magna aliqua.', 592 'test', 593 'foo']], 4], 594 b: new Map([['za', 1], ['zb', 'test']]) 595}; 596console.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 })); 597 598// { a: 599// [ 1, 600// 2, 601// [ [ 'Lorem ipsum dolor sit amet, consectetur [...]', // A long line 602// 'test', 603// 'foo' ] ], 604// 4 ], 605// b: Map { 'za' => 1, 'zb' => 'test' } } 606 607// Setting `compact` to false changes the output to be more reader friendly. 608console.log(util.inspect(o, { compact: false, depth: 5, breakLength: 80 })); 609 610// { 611// a: [ 612// 1, 613// 2, 614// [ 615// [ 616// 'Lorem ipsum dolor sit amet, consectetur ' + 617// 'adipiscing elit, sed do eiusmod tempor ' + 618// 'incididunt ut labore et dolore magna ' + 619// 'aliqua., 620// 'test', 621// 'foo' 622// ] 623// ], 624// 4 625// ], 626// b: Map { 627// 'za' => 1, 628// 'zb' => 'test' 629// } 630// } 631 632// Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a 633// single line. 634// Reducing the `breakLength` will split the "Lorem ipsum" text in smaller 635// chunks. 636``` 637 638The `showHidden` option allows [`WeakMap`][] and [`WeakSet`][] entries to be 639inspected. If there are more entries than `maxArrayLength`, there is no 640guarantee which entries are displayed. That means retrieving the same 641[`WeakSet`][] entries twice may result in different output. Furthermore, entries 642with no remaining strong references may be garbage collected at any time. 643 644```js 645const { inspect } = require('util'); 646 647const obj = { a: 1 }; 648const obj2 = { b: 2 }; 649const weakSet = new WeakSet([obj, obj2]); 650 651console.log(inspect(weakSet, { showHidden: true })); 652// WeakSet { { a: 1 }, { b: 2 } } 653``` 654 655The `sorted` option ensures that an object's property insertion order does not 656impact the result of `util.inspect()`. 657 658```js 659const { inspect } = require('util'); 660const assert = require('assert'); 661 662const o1 = { 663 b: [2, 3, 1], 664 a: '`a` comes before `b`', 665 c: new Set([2, 3, 1]) 666}; 667console.log(inspect(o1, { sorted: true })); 668// { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set { 1, 2, 3 } } 669console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) })); 670// { c: Set { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' } 671 672const o2 = { 673 c: new Set([2, 1, 3]), 674 a: '`a` comes before `b`', 675 b: [2, 3, 1] 676}; 677assert.strict.equal( 678 inspect(o1, { sorted: true }), 679 inspect(o2, { sorted: true }) 680); 681``` 682 683`util.inspect()` is a synchronous method intended for debugging. Its maximum 684output length is approximately 128 MB. Inputs that result in longer output will 685be truncated. 686 687### Customizing `util.inspect` colors 688 689<!-- type=misc --> 690 691Color output (if enabled) of `util.inspect` is customizable globally 692via the `util.inspect.styles` and `util.inspect.colors` properties. 693 694`util.inspect.styles` is a map associating a style name to a color from 695`util.inspect.colors`. 696 697The default styles and associated colors are: 698 699* `bigint`: `yellow` 700* `boolean`: `yellow` 701* `date`: `magenta` 702* `module`: `underline` 703* `name`: (no styling) 704* `null`: `bold` 705* `number`: `yellow` 706* `regexp`: `red` 707* `special`: `cyan` (e.g., `Proxies`) 708* `string`: `green` 709* `symbol`: `green` 710* `undefined`: `grey` 711 712Color styling uses ANSI control codes that may not be supported on all 713terminals. To verify color support use [`tty.hasColors()`][]. 714 715Predefined control codes are listed below (grouped as "Modifiers", "Foreground 716colors", and "Background colors"). 717 718#### Modifiers 719 720Modifier support varies throughout different terminals. They will mostly be 721ignored, if not supported. 722 723* `reset` - Resets all (color) modifiers to their defaults 724* **bold** - Make text bold 725* _italic_ - Make text italic 726* <span style="border-bottom: 1px;">underline</span> - Make text underlined 727* ~~strikethrough~~ - Puts a horizontal line through the center of the text 728 (Alias: `strikeThrough`, `crossedout`, `crossedOut`) 729* `hidden` - Prints the text, but makes it invisible (Alias: conceal) 730* <span style="opacity: 0.5;">dim</span> - Decreased color intensity (Alias: 731 `faint`) 732* <span style="border-top: 1px">overlined</span> - Make text overlined 733* blink - Hides and shows the text in an interval 734* <span style="filter: invert(100%)">inverse</span> - Swap foreground and 735 background colors (Alias: `swapcolors`, `swapColors`) 736* <span style="border-bottom: 1px double;">doubleunderline</span> - Make text 737 double underlined (Alias: `doubleUnderline`) 738* <span style="border: 1px">framed</span> - Draw a frame around the text 739 740#### Foreground colors 741 742* `black` 743* `red` 744* `green` 745* `yellow` 746* `blue` 747* `magenta` 748* `cyan` 749* `white` 750* `gray` (alias: `grey`, `blackBright`) 751* `redBright` 752* `greenBright` 753* `yellowBright` 754* `blueBright` 755* `magentaBright` 756* `cyanBright` 757* `whiteBright` 758 759#### Background colors 760 761* `bgBlack` 762* `bgRed` 763* `bgGreen` 764* `bgYellow` 765* `bgBlue` 766* `bgMagenta` 767* `bgCyan` 768* `bgWhite` 769* `bgGray` (alias: `bgGrey`, `bgBlackBright`) 770* `bgRedBright` 771* `bgGreenBright` 772* `bgYellowBright` 773* `bgBlueBright` 774* `bgMagentaBright` 775* `bgCyanBright` 776* `bgWhiteBright` 777 778### Custom inspection functions on objects 779 780<!-- type=misc --> 781 782Objects may also define their own 783[`[util.inspect.custom](depth, opts)`][util.inspect.custom] function, 784which `util.inspect()` will invoke and use the result of when inspecting 785the object: 786 787```js 788const util = require('util'); 789 790class Box { 791 constructor(value) { 792 this.value = value; 793 } 794 795 [util.inspect.custom](depth, options) { 796 if (depth < 0) { 797 return options.stylize('[Box]', 'special'); 798 } 799 800 const newOptions = Object.assign({}, options, { 801 depth: options.depth === null ? null : options.depth - 1 802 }); 803 804 // Five space padding because that's the size of "Box< ". 805 const padding = ' '.repeat(5); 806 const inner = util.inspect(this.value, newOptions) 807 .replace(/\n/g, `\n${padding}`); 808 return `${options.stylize('Box', 'special')}< ${inner} >`; 809 } 810} 811 812const box = new Box(true); 813 814util.inspect(box); 815// Returns: "Box< true >" 816``` 817 818Custom `[util.inspect.custom](depth, opts)` functions typically return a string 819but may return a value of any type that will be formatted accordingly by 820`util.inspect()`. 821 822```js 823const util = require('util'); 824 825const obj = { foo: 'this will not show up in the inspect() output' }; 826obj[util.inspect.custom] = (depth) => { 827 return { bar: 'baz' }; 828}; 829 830util.inspect(obj); 831// Returns: "{ bar: 'baz' }" 832``` 833 834### `util.inspect.custom` 835<!-- YAML 836added: v6.6.0 837changes: 838 - version: v10.12.0 839 pr-url: https://github.com/nodejs/node/pull/20857 840 description: This is now defined as a shared symbol. 841--> 842 843* {symbol} that can be used to declare custom inspect functions. 844 845In addition to being accessible through `util.inspect.custom`, this 846symbol is [registered globally][global symbol registry] and can be 847accessed in any environment as `Symbol.for('nodejs.util.inspect.custom')`. 848 849```js 850const inspect = Symbol.for('nodejs.util.inspect.custom'); 851 852class Password { 853 constructor(value) { 854 this.value = value; 855 } 856 857 toString() { 858 return 'xxxxxxxx'; 859 } 860 861 [inspect]() { 862 return `Password <${this.toString()}>`; 863 } 864} 865 866const password = new Password('r0sebud'); 867console.log(password); 868// Prints Password <xxxxxxxx> 869``` 870 871See [Custom inspection functions on Objects][] for more details. 872 873### `util.inspect.defaultOptions` 874<!-- YAML 875added: v6.4.0 876--> 877 878The `defaultOptions` value allows customization of the default options used by 879`util.inspect`. This is useful for functions like `console.log` or 880`util.format` which implicitly call into `util.inspect`. It shall be set to an 881object containing one or more valid [`util.inspect()`][] options. Setting 882option properties directly is also supported. 883 884```js 885const util = require('util'); 886const arr = Array(101).fill(0); 887 888console.log(arr); // Logs the truncated array 889util.inspect.defaultOptions.maxArrayLength = null; 890console.log(arr); // logs the full array 891``` 892 893## `util.isDeepStrictEqual(val1, val2)` 894<!-- YAML 895added: v9.0.0 896--> 897 898* `val1` {any} 899* `val2` {any} 900* Returns: {boolean} 901 902Returns `true` if there is deep strict equality between `val1` and `val2`. 903Otherwise, returns `false`. 904 905See [`assert.deepStrictEqual()`][] for more information about deep strict 906equality. 907 908## `util.promisify(original)` 909<!-- YAML 910added: v8.0.0 911--> 912 913* `original` {Function} 914* Returns: {Function} 915 916Takes a function following the common error-first callback style, i.e. taking 917an `(err, value) => ...` callback as the last argument, and returns a version 918that returns promises. 919 920```js 921const util = require('util'); 922const fs = require('fs'); 923 924const stat = util.promisify(fs.stat); 925stat('.').then((stats) => { 926 // Do something with `stats` 927}).catch((error) => { 928 // Handle the error. 929}); 930``` 931 932Or, equivalently using `async function`s: 933 934```js 935const util = require('util'); 936const fs = require('fs'); 937 938const stat = util.promisify(fs.stat); 939 940async function callStat() { 941 const stats = await stat('.'); 942 console.log(`This directory is owned by ${stats.uid}`); 943} 944``` 945 946If there is an `original[util.promisify.custom]` property present, `promisify` 947will return its value, see [Custom promisified functions][]. 948 949`promisify()` assumes that `original` is a function taking a callback as its 950final argument in all cases. If `original` is not a function, `promisify()` 951will throw an error. If `original` is a function but its last argument is not 952an error-first callback, it will still be passed an error-first 953callback as its last argument. 954 955Using `promisify()` on class methods or other methods that use `this` may not 956work as expected unless handled specially: 957 958```js 959const util = require('util'); 960 961class Foo { 962 constructor() { 963 this.a = 42; 964 } 965 966 bar(callback) { 967 callback(null, this.a); 968 } 969} 970 971const foo = new Foo(); 972 973const naiveBar = util.promisify(foo.bar); 974// TypeError: Cannot read property 'a' of undefined 975// naiveBar().then(a => console.log(a)); 976 977naiveBar.call(foo).then((a) => console.log(a)); // '42' 978 979const bindBar = naiveBar.bind(foo); 980bindBar().then((a) => console.log(a)); // '42' 981``` 982 983### Custom promisified functions 984 985Using the `util.promisify.custom` symbol one can override the return value of 986[`util.promisify()`][]: 987 988```js 989const util = require('util'); 990 991function doSomething(foo, callback) { 992 // ... 993} 994 995doSomething[util.promisify.custom] = (foo) => { 996 return getPromiseSomehow(); 997}; 998 999const promisified = util.promisify(doSomething); 1000console.log(promisified === doSomething[util.promisify.custom]); 1001// prints 'true' 1002``` 1003 1004This can be useful for cases where the original function does not follow the 1005standard format of taking an error-first callback as the last argument. 1006 1007For example, with a function that takes in 1008`(foo, onSuccessCallback, onErrorCallback)`: 1009 1010```js 1011doSomething[util.promisify.custom] = (foo) => { 1012 return new Promise((resolve, reject) => { 1013 doSomething(foo, resolve, reject); 1014 }); 1015}; 1016``` 1017 1018If `promisify.custom` is defined but is not a function, `promisify()` will 1019throw an error. 1020 1021### `util.promisify.custom` 1022<!-- YAML 1023added: v8.0.0 1024changes: 1025 - version: v12.16.2 1026 pr-url: https://github.com/nodejs/node/pull/31672 1027 description: This is now defined as a shared symbol. 1028--> 1029 1030* {symbol} that can be used to declare custom promisified variants of functions, 1031see [Custom promisified functions][]. 1032 1033In addition to being accessible through `util.promisify.custom`, this 1034symbol is [registered globally][global symbol registry] and can be 1035accessed in any environment as `Symbol.for('nodejs.util.promisify.custom')`. 1036 1037For example, with a function that takes in 1038`(foo, onSuccessCallback, onErrorCallback)`: 1039 1040```js 1041const kCustomPromisifiedSymbol = Symbol.for('nodejs.util.promisify.custom'); 1042 1043doSomething[kCustomPromisifiedSymbol] = (foo) => { 1044 return new Promise((resolve, reject) => { 1045 doSomething(foo, resolve, reject); 1046 }); 1047}; 1048``` 1049 1050## Class: `util.TextDecoder` 1051<!-- YAML 1052added: v8.3.0 1053--> 1054 1055An implementation of the [WHATWG Encoding Standard][] `TextDecoder` API. 1056 1057```js 1058const decoder = new TextDecoder('shift_jis'); 1059let string = ''; 1060let buffer; 1061while (buffer = getNextChunkSomehow()) { 1062 string += decoder.decode(buffer, { stream: true }); 1063} 1064string += decoder.decode(); // end-of-stream 1065``` 1066 1067### WHATWG supported encodings 1068 1069Per the [WHATWG Encoding Standard][], the encodings supported by the 1070`TextDecoder` API are outlined in the tables below. For each encoding, 1071one or more aliases may be used. 1072 1073Different Node.js build configurations support different sets of encodings. 1074While a very basic set of encodings is supported even on Node.js builds without 1075ICU enabled, support for some encodings is provided only when Node.js is built 1076with ICU and using the full ICU data (see [Internationalization][]). 1077 1078#### Encodings Supported Without ICU 1079 1080| Encoding | Aliases | 1081| ----------- | --------------------------------- | 1082| `'utf-8'` | `'unicode-1-1-utf-8'`, `'utf8'` | 1083| `'utf-16le'` | `'utf-16'` | 1084 1085#### Encodings Supported by Default (With ICU) 1086 1087| Encoding | Aliases | 1088| ----------- | --------------------------------- | 1089| `'utf-8'` | `'unicode-1-1-utf-8'`, `'utf8'` | 1090| `'utf-16le'` | `'utf-16'` | 1091| `'utf-16be'` | | 1092 1093#### Encodings requiring full ICU data 1094 1095| Encoding | Aliases | 1096| ----------------- | -------------------------------- | 1097| `'ibm866'` | `'866'`, `'cp866'`, `'csibm866'` | 1098| `'iso-8859-2'` | `'csisolatin2'`, `'iso-ir-101'`, `'iso8859-2'`, `'iso88592'`, `'iso_8859-2'`, `'iso_8859-2:1987'`, `'l2'`, `'latin2'` | 1099| `'iso-8859-3'` | `'csisolatin3'`, `'iso-ir-109'`, `'iso8859-3'`, `'iso88593'`, `'iso_8859-3'`, `'iso_8859-3:1988'`, `'l3'`, `'latin3'` | 1100| `'iso-8859-4'` | `'csisolatin4'`, `'iso-ir-110'`, `'iso8859-4'`, `'iso88594'`, `'iso_8859-4'`, `'iso_8859-4:1988'`, `'l4'`, `'latin4'` | 1101| `'iso-8859-5'` | `'csisolatincyrillic'`, `'cyrillic'`, `'iso-ir-144'`, `'iso8859-5'`, `'iso88595'`, `'iso_8859-5'`, `'iso_8859-5:1988'` | 1102| `'iso-8859-6'` | `'arabic'`, `'asmo-708'`, `'csiso88596e'`, `'csiso88596i'`, `'csisolatinarabic'`, `'ecma-114'`, `'iso-8859-6-e'`, `'iso-8859-6-i'`, `'iso-ir-127'`, `'iso8859-6'`, `'iso88596'`, `'iso_8859-6'`, `'iso_8859-6:1987'` | 1103| `'iso-8859-7'` | `'csisolatingreek'`, `'ecma-118'`, `'elot_928'`, `'greek'`, `'greek8'`, `'iso-ir-126'`, `'iso8859-7'`, `'iso88597'`, `'iso_8859-7'`, `'iso_8859-7:1987'`, `'sun_eu_greek'` | 1104| `'iso-8859-8'` | `'csiso88598e'`, `'csisolatinhebrew'`, `'hebrew'`, `'iso-8859-8-e'`, `'iso-ir-138'`, `'iso8859-8'`, `'iso88598'`, `'iso_8859-8'`, `'iso_8859-8:1988'`, `'visual'` | 1105| `'iso-8859-8-i'` | `'csiso88598i'`, `'logical'` | 1106| `'iso-8859-10'` | `'csisolatin6'`, `'iso-ir-157'`, `'iso8859-10'`, `'iso885910'`, `'l6'`, `'latin6'` | 1107| `'iso-8859-13'` | `'iso8859-13'`, `'iso885913'` | 1108| `'iso-8859-14'` | `'iso8859-14'`, `'iso885914'` | 1109| `'iso-8859-15'` | `'csisolatin9'`, `'iso8859-15'`, `'iso885915'`, `'iso_8859-15'`, `'l9'` | 1110| `'koi8-r'` | `'cskoi8r'`, `'koi'`, `'koi8'`, `'koi8_r'` | 1111| `'koi8-u'` | `'koi8-ru'` | 1112| `'macintosh'` | `'csmacintosh'`, `'mac'`, `'x-mac-roman'` | 1113| `'windows-874'` | `'dos-874'`, `'iso-8859-11'`, `'iso8859-11'`, `'iso885911'`, `'tis-620'` | 1114| `'windows-1250'` | `'cp1250'`, `'x-cp1250'` | 1115| `'windows-1251'` | `'cp1251'`, `'x-cp1251'` | 1116| `'windows-1252'` | `'ansi_x3.4-1968'`, `'ascii'`, `'cp1252'`, `'cp819'`, `'csisolatin1'`, `'ibm819'`, `'iso-8859-1'`, `'iso-ir-100'`, `'iso8859-1'`, `'iso88591'`, `'iso_8859-1'`, `'iso_8859-1:1987'`, `'l1'`, `'latin1'`, `'us-ascii'`, `'x-cp1252'` | 1117| `'windows-1253'` | `'cp1253'`, `'x-cp1253'` | 1118| `'windows-1254'` | `'cp1254'`, `'csisolatin5'`, `'iso-8859-9'`, `'iso-ir-148'`, `'iso8859-9'`, `'iso88599'`, `'iso_8859-9'`, `'iso_8859-9:1989'`, `'l5'`, `'latin5'`, `'x-cp1254'` | 1119| `'windows-1255'` | `'cp1255'`, `'x-cp1255'` | 1120| `'windows-1256'` | `'cp1256'`, `'x-cp1256'` | 1121| `'windows-1257'` | `'cp1257'`, `'x-cp1257'` | 1122| `'windows-1258'` | `'cp1258'`, `'x-cp1258'` | 1123| `'x-mac-cyrillic'` | `'x-mac-ukrainian'` | 1124| `'gbk'` | `'chinese'`, `'csgb2312'`, `'csiso58gb231280'`, `'gb2312'`, `'gb_2312'`, `'gb_2312-80'`, `'iso-ir-58'`, `'x-gbk'` | 1125| `'gb18030'` | | 1126| `'big5'` | `'big5-hkscs'`, `'cn-big5'`, `'csbig5'`, `'x-x-big5'` | 1127| `'euc-jp'` | `'cseucpkdfmtjapanese'`, `'x-euc-jp'` | 1128| `'iso-2022-jp'` | `'csiso2022jp'` | 1129| `'shift_jis'` | `'csshiftjis'`, `'ms932'`, `'ms_kanji'`, `'shift-jis'`, `'sjis'`, `'windows-31j'`, `'x-sjis'` | 1130| `'euc-kr'` | `'cseuckr'`, `'csksc56011987'`, `'iso-ir-149'`, `'korean'`, `'ks_c_5601-1987'`, `'ks_c_5601-1989'`, `'ksc5601'`, `'ksc_5601'`, `'windows-949'` | 1131 1132The `'iso-8859-16'` encoding listed in the [WHATWG Encoding Standard][] 1133is not supported. 1134 1135### `new TextDecoder([encoding[, options]])` 1136<!-- YAML 1137added: v8.3.0 1138changes: 1139 - version: v11.0.0 1140 pr-url: v11.0.0 1141 description: The class is now available on the global object. 1142--> 1143 1144* `encoding` {string} Identifies the `encoding` that this `TextDecoder` instance 1145 supports. **Default:** `'utf-8'`. 1146* `options` {Object} 1147 * `fatal` {boolean} `true` if decoding failures are fatal. This option is only 1148 supported when ICU is enabled (see [Internationalization][]). **Default:** 1149 `false`. 1150 * `ignoreBOM` {boolean} When `true`, the `TextDecoder` will include the byte 1151 order mark in the decoded result. When `false`, the byte order mark will 1152 be removed from the output. This option is only used when `encoding` is 1153 `'utf-8'`, `'utf-16be'` or `'utf-16le'`. **Default:** `false`. 1154 1155Creates an new `TextDecoder` instance. The `encoding` may specify one of the 1156supported encodings or an alias. 1157 1158The `TextDecoder` class is also available on the global object. 1159 1160### `textDecoder.decode([input[, options]])` 1161 1162* `input` {ArrayBuffer|DataView|TypedArray} An `ArrayBuffer`, `DataView` or 1163 `TypedArray` instance containing the encoded data. 1164* `options` {Object} 1165 * `stream` {boolean} `true` if additional chunks of data are expected. 1166 **Default:** `false`. 1167* Returns: {string} 1168 1169Decodes the `input` and returns a string. If `options.stream` is `true`, any 1170incomplete byte sequences occurring at the end of the `input` are buffered 1171internally and emitted after the next call to `textDecoder.decode()`. 1172 1173If `textDecoder.fatal` is `true`, decoding errors that occur will result in a 1174`TypeError` being thrown. 1175 1176### `textDecoder.encoding` 1177 1178* {string} 1179 1180The encoding supported by the `TextDecoder` instance. 1181 1182### `textDecoder.fatal` 1183 1184* {boolean} 1185 1186The value will be `true` if decoding errors result in a `TypeError` being 1187thrown. 1188 1189### `textDecoder.ignoreBOM` 1190 1191* {boolean} 1192 1193The value will be `true` if the decoding result will include the byte order 1194mark. 1195 1196## Class: `util.TextEncoder` 1197<!-- YAML 1198added: v8.3.0 1199changes: 1200 - version: v11.0.0 1201 pr-url: v11.0.0 1202 description: The class is now available on the global object. 1203--> 1204 1205An implementation of the [WHATWG Encoding Standard][] `TextEncoder` API. All 1206instances of `TextEncoder` only support UTF-8 encoding. 1207 1208```js 1209const encoder = new TextEncoder(); 1210const uint8array = encoder.encode('this is some data'); 1211``` 1212 1213The `TextEncoder` class is also available on the global object. 1214 1215### `textEncoder.encode([input])` 1216 1217* `input` {string} The text to encode. **Default:** an empty string. 1218* Returns: {Uint8Array} 1219 1220UTF-8 encodes the `input` string and returns a `Uint8Array` containing the 1221encoded bytes. 1222 1223### `textEncoder.encodeInto(src, dest)` 1224 1225* `src` {string} The text to encode. 1226* `dest` {Uint8Array} The array to hold the encode result. 1227* Returns: {Object} 1228 * `read` {number} The read Unicode code units of src. 1229 * `written` {number} The written UTF-8 bytes of dest. 1230 1231UTF-8 encodes the `src` string to the `dest` Uint8Array and returns an object 1232containing the read Unicode code units and written UTF-8 bytes. 1233 1234```js 1235const encoder = new TextEncoder(); 1236const src = 'this is some data'; 1237const dest = new Uint8Array(10); 1238const { read, written } = encoder.encodeInto(src, dest); 1239``` 1240 1241### `textEncoder.encoding` 1242 1243* {string} 1244 1245The encoding supported by the `TextEncoder` instance. Always set to `'utf-8'`. 1246 1247## `util.types` 1248<!-- YAML 1249added: v10.0.0 1250--> 1251 1252`util.types` provides type checks for different kinds of built-in objects. 1253Unlike `instanceof` or `Object.prototype.toString.call(value)`, these checks do 1254not inspect properties of the object that are accessible from JavaScript (like 1255their prototype), and usually have the overhead of calling into C++. 1256 1257The result generally does not make any guarantees about what kinds of 1258properties or behavior a value exposes in JavaScript. They are primarily 1259useful for addon developers who prefer to do type checking in JavaScript. 1260 1261### `util.types.isAnyArrayBuffer(value)` 1262<!-- YAML 1263added: v10.0.0 1264--> 1265 1266* `value` {any} 1267* Returns: {boolean} 1268 1269Returns `true` if the value is a built-in [`ArrayBuffer`][] or 1270[`SharedArrayBuffer`][] instance. 1271 1272See also [`util.types.isArrayBuffer()`][] and 1273[`util.types.isSharedArrayBuffer()`][]. 1274 1275```js 1276util.types.isAnyArrayBuffer(new ArrayBuffer()); // Returns true 1277util.types.isAnyArrayBuffer(new SharedArrayBuffer()); // Returns true 1278``` 1279 1280### `util.types.isArrayBufferView(value)` 1281<!-- YAML 1282added: v10.0.0 1283--> 1284 1285* `value` {any} 1286* Returns: {boolean} 1287 1288Returns `true` if the value is an instance of one of the [`ArrayBuffer`][] 1289views, such as typed array objects or [`DataView`][]. Equivalent to 1290[`ArrayBuffer.isView()`][]. 1291 1292```js 1293util.types.isArrayBufferView(new Int8Array()); // true 1294util.types.isArrayBufferView(Buffer.from('hello world')); // true 1295util.types.isArrayBufferView(new DataView(new ArrayBuffer(16))); // true 1296util.types.isArrayBufferView(new ArrayBuffer()); // false 1297``` 1298 1299### `util.types.isArgumentsObject(value)` 1300<!-- YAML 1301added: v10.0.0 1302--> 1303 1304* `value` {any} 1305* Returns: {boolean} 1306 1307Returns `true` if the value is an `arguments` object. 1308 1309<!-- eslint-disable prefer-rest-params --> 1310```js 1311function foo() { 1312 util.types.isArgumentsObject(arguments); // Returns true 1313} 1314``` 1315 1316### `util.types.isArrayBuffer(value)` 1317<!-- YAML 1318added: v10.0.0 1319--> 1320 1321* `value` {any} 1322* Returns: {boolean} 1323 1324Returns `true` if the value is a built-in [`ArrayBuffer`][] instance. 1325This does *not* include [`SharedArrayBuffer`][] instances. Usually, it is 1326desirable to test for both; See [`util.types.isAnyArrayBuffer()`][] for that. 1327 1328```js 1329util.types.isArrayBuffer(new ArrayBuffer()); // Returns true 1330util.types.isArrayBuffer(new SharedArrayBuffer()); // Returns false 1331``` 1332 1333### `util.types.isAsyncFunction(value)` 1334<!-- YAML 1335added: v10.0.0 1336--> 1337 1338* `value` {any} 1339* Returns: {boolean} 1340 1341Returns `true` if the value is an [async function][]. 1342This only reports back what the JavaScript engine is seeing; 1343in particular, the return value may not match the original source code if 1344a transpilation tool was used. 1345 1346```js 1347util.types.isAsyncFunction(function foo() {}); // Returns false 1348util.types.isAsyncFunction(async function foo() {}); // Returns true 1349``` 1350 1351### `util.types.isBigInt64Array(value)` 1352<!-- YAML 1353added: v10.0.0 1354--> 1355 1356* `value` {any} 1357* Returns: {boolean} 1358 1359Returns `true` if the value is a `BigInt64Array` instance. 1360 1361```js 1362util.types.isBigInt64Array(new BigInt64Array()); // Returns true 1363util.types.isBigInt64Array(new BigUint64Array()); // Returns false 1364``` 1365 1366### `util.types.isBigUint64Array(value)` 1367<!-- YAML 1368added: v10.0.0 1369--> 1370 1371* `value` {any} 1372* Returns: {boolean} 1373 1374Returns `true` if the value is a `BigUint64Array` instance. 1375 1376```js 1377util.types.isBigUint64Array(new BigInt64Array()); // Returns false 1378util.types.isBigUint64Array(new BigUint64Array()); // Returns true 1379``` 1380 1381### `util.types.isBooleanObject(value)` 1382<!-- YAML 1383added: v10.0.0 1384--> 1385 1386* `value` {any} 1387* Returns: {boolean} 1388 1389Returns `true` if the value is a boolean object, e.g. created 1390by `new Boolean()`. 1391 1392```js 1393util.types.isBooleanObject(false); // Returns false 1394util.types.isBooleanObject(true); // Returns false 1395util.types.isBooleanObject(new Boolean(false)); // Returns true 1396util.types.isBooleanObject(new Boolean(true)); // Returns true 1397util.types.isBooleanObject(Boolean(false)); // Returns false 1398util.types.isBooleanObject(Boolean(true)); // Returns false 1399``` 1400 1401### `util.types.isBoxedPrimitive(value)` 1402<!-- YAML 1403added: v10.11.0 1404--> 1405 1406* `value` {any} 1407* Returns: {boolean} 1408 1409Returns `true` if the value is any boxed primitive object, e.g. created 1410by `new Boolean()`, `new String()` or `Object(Symbol())`. 1411 1412For example: 1413 1414```js 1415util.types.isBoxedPrimitive(false); // Returns false 1416util.types.isBoxedPrimitive(new Boolean(false)); // Returns true 1417util.types.isBoxedPrimitive(Symbol('foo')); // Returns false 1418util.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true 1419util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true 1420``` 1421 1422### `util.types.isDataView(value)` 1423<!-- YAML 1424added: v10.0.0 1425--> 1426 1427* `value` {any} 1428* Returns: {boolean} 1429 1430Returns `true` if the value is a built-in [`DataView`][] instance. 1431 1432```js 1433const ab = new ArrayBuffer(20); 1434util.types.isDataView(new DataView(ab)); // Returns true 1435util.types.isDataView(new Float64Array()); // Returns false 1436``` 1437 1438See also [`ArrayBuffer.isView()`][]. 1439 1440### `util.types.isDate(value)` 1441<!-- YAML 1442added: v10.0.0 1443--> 1444 1445* `value` {any} 1446* Returns: {boolean} 1447 1448Returns `true` if the value is a built-in [`Date`][] instance. 1449 1450```js 1451util.types.isDate(new Date()); // Returns true 1452``` 1453 1454### `util.types.isExternal(value)` 1455<!-- YAML 1456added: v10.0.0 1457--> 1458 1459* `value` {any} 1460* Returns: {boolean} 1461 1462Returns `true` if the value is a native `External` value. 1463 1464A native `External` value is a special type of object that contains a 1465raw C++ pointer (`void*`) for access from native code, and has no other 1466properties. Such objects are created either by Node.js internals or native 1467addons. In JavaScript, they are [frozen][`Object.freeze()`] objects with a 1468`null` prototype. 1469 1470```c 1471#include <js_native_api.h> 1472#include <stdlib.h> 1473napi_value result; 1474static napi_value MyNapi(napi_env env, napi_callback_info info) { 1475 int* raw = (int*) malloc(1024); 1476 napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result); 1477 if (status != napi_ok) { 1478 napi_throw_error(env, NULL, "napi_create_external failed"); 1479 return NULL; 1480 } 1481 return result; 1482} 1483... 1484DECLARE_NAPI_PROPERTY("myNapi", MyNapi) 1485... 1486``` 1487 1488```js 1489const native = require('napi_addon.node'); 1490const data = native.myNapi(); 1491util.types.isExternal(data); // returns true 1492util.types.isExternal(0); // returns false 1493util.types.isExternal(new String('foo')); // returns false 1494``` 1495 1496For further information on `napi_create_external`, refer to 1497[`napi_create_external()`][]. 1498 1499### `util.types.isFloat32Array(value)` 1500<!-- YAML 1501added: v10.0.0 1502--> 1503 1504* `value` {any} 1505* Returns: {boolean} 1506 1507Returns `true` if the value is a built-in [`Float32Array`][] instance. 1508 1509```js 1510util.types.isFloat32Array(new ArrayBuffer()); // Returns false 1511util.types.isFloat32Array(new Float32Array()); // Returns true 1512util.types.isFloat32Array(new Float64Array()); // Returns false 1513``` 1514 1515### `util.types.isFloat64Array(value)` 1516<!-- YAML 1517added: v10.0.0 1518--> 1519 1520* `value` {any} 1521* Returns: {boolean} 1522 1523Returns `true` if the value is a built-in [`Float64Array`][] instance. 1524 1525```js 1526util.types.isFloat64Array(new ArrayBuffer()); // Returns false 1527util.types.isFloat64Array(new Uint8Array()); // Returns false 1528util.types.isFloat64Array(new Float64Array()); // Returns true 1529``` 1530 1531### `util.types.isGeneratorFunction(value)` 1532<!-- YAML 1533added: v10.0.0 1534--> 1535 1536* `value` {any} 1537* Returns: {boolean} 1538 1539Returns `true` if the value is a generator function. 1540This only reports back what the JavaScript engine is seeing; 1541in particular, the return value may not match the original source code if 1542a transpilation tool was used. 1543 1544```js 1545util.types.isGeneratorFunction(function foo() {}); // Returns false 1546util.types.isGeneratorFunction(function* foo() {}); // Returns true 1547``` 1548 1549### `util.types.isGeneratorObject(value)` 1550<!-- YAML 1551added: v10.0.0 1552--> 1553 1554* `value` {any} 1555* Returns: {boolean} 1556 1557Returns `true` if the value is a generator object as returned from a 1558built-in generator function. 1559This only reports back what the JavaScript engine is seeing; 1560in particular, the return value may not match the original source code if 1561a transpilation tool was used. 1562 1563```js 1564function* foo() {} 1565const generator = foo(); 1566util.types.isGeneratorObject(generator); // Returns true 1567``` 1568 1569### `util.types.isInt8Array(value)` 1570<!-- YAML 1571added: v10.0.0 1572--> 1573 1574* `value` {any} 1575* Returns: {boolean} 1576 1577Returns `true` if the value is a built-in [`Int8Array`][] instance. 1578 1579```js 1580util.types.isInt8Array(new ArrayBuffer()); // Returns false 1581util.types.isInt8Array(new Int8Array()); // Returns true 1582util.types.isInt8Array(new Float64Array()); // Returns false 1583``` 1584 1585### `util.types.isInt16Array(value)` 1586<!-- YAML 1587added: v10.0.0 1588--> 1589 1590* `value` {any} 1591* Returns: {boolean} 1592 1593Returns `true` if the value is a built-in [`Int16Array`][] instance. 1594 1595```js 1596util.types.isInt16Array(new ArrayBuffer()); // Returns false 1597util.types.isInt16Array(new Int16Array()); // Returns true 1598util.types.isInt16Array(new Float64Array()); // Returns false 1599``` 1600 1601### `util.types.isInt32Array(value)` 1602<!-- YAML 1603added: v10.0.0 1604--> 1605 1606* `value` {any} 1607* Returns: {boolean} 1608 1609Returns `true` if the value is a built-in [`Int32Array`][] instance. 1610 1611```js 1612util.types.isInt32Array(new ArrayBuffer()); // Returns false 1613util.types.isInt32Array(new Int32Array()); // Returns true 1614util.types.isInt32Array(new Float64Array()); // Returns false 1615``` 1616 1617### `util.types.isMap(value)` 1618<!-- YAML 1619added: v10.0.0 1620--> 1621 1622* `value` {any} 1623* Returns: {boolean} 1624 1625Returns `true` if the value is a built-in [`Map`][] instance. 1626 1627```js 1628util.types.isMap(new Map()); // Returns true 1629``` 1630 1631### `util.types.isMapIterator(value)` 1632<!-- YAML 1633added: v10.0.0 1634--> 1635 1636* `value` {any} 1637* Returns: {boolean} 1638 1639Returns `true` if the value is an iterator returned for a built-in 1640[`Map`][] instance. 1641 1642```js 1643const map = new Map(); 1644util.types.isMapIterator(map.keys()); // Returns true 1645util.types.isMapIterator(map.values()); // Returns true 1646util.types.isMapIterator(map.entries()); // Returns true 1647util.types.isMapIterator(map[Symbol.iterator]()); // Returns true 1648``` 1649 1650### `util.types.isModuleNamespaceObject(value)` 1651<!-- YAML 1652added: v10.0.0 1653--> 1654 1655* `value` {any} 1656* Returns: {boolean} 1657 1658Returns `true` if the value is an instance of a [Module Namespace Object][]. 1659 1660<!-- eslint-skip --> 1661```js 1662import * as ns from './a.js'; 1663 1664util.types.isModuleNamespaceObject(ns); // Returns true 1665``` 1666 1667### `util.types.isNativeError(value)` 1668<!-- YAML 1669added: v10.0.0 1670--> 1671 1672* `value` {any} 1673* Returns: {boolean} 1674 1675Returns `true` if the value is an instance of a built-in [`Error`][] type. 1676 1677```js 1678util.types.isNativeError(new Error()); // Returns true 1679util.types.isNativeError(new TypeError()); // Returns true 1680util.types.isNativeError(new RangeError()); // Returns true 1681``` 1682 1683### `util.types.isNumberObject(value)` 1684<!-- YAML 1685added: v10.0.0 1686--> 1687 1688* `value` {any} 1689* Returns: {boolean} 1690 1691Returns `true` if the value is a number object, e.g. created 1692by `new Number()`. 1693 1694```js 1695util.types.isNumberObject(0); // Returns false 1696util.types.isNumberObject(new Number(0)); // Returns true 1697``` 1698 1699### `util.types.isPromise(value)` 1700<!-- YAML 1701added: v10.0.0 1702--> 1703 1704* `value` {any} 1705* Returns: {boolean} 1706 1707Returns `true` if the value is a built-in [`Promise`][]. 1708 1709```js 1710util.types.isPromise(Promise.resolve(42)); // Returns true 1711``` 1712 1713### `util.types.isProxy(value)` 1714<!-- YAML 1715added: v10.0.0 1716--> 1717 1718* `value` {any} 1719* Returns: {boolean} 1720 1721Returns `true` if the value is a [`Proxy`][] instance. 1722 1723```js 1724const target = {}; 1725const proxy = new Proxy(target, {}); 1726util.types.isProxy(target); // Returns false 1727util.types.isProxy(proxy); // Returns true 1728``` 1729 1730### `util.types.isRegExp(value)` 1731<!-- YAML 1732added: v10.0.0 1733--> 1734 1735* `value` {any} 1736* Returns: {boolean} 1737 1738Returns `true` if the value is a regular expression object. 1739 1740```js 1741util.types.isRegExp(/abc/); // Returns true 1742util.types.isRegExp(new RegExp('abc')); // Returns true 1743``` 1744 1745### `util.types.isSet(value)` 1746<!-- YAML 1747added: v10.0.0 1748--> 1749 1750* `value` {any} 1751* Returns: {boolean} 1752 1753Returns `true` if the value is a built-in [`Set`][] instance. 1754 1755```js 1756util.types.isSet(new Set()); // Returns true 1757``` 1758 1759### `util.types.isSetIterator(value)` 1760<!-- YAML 1761added: v10.0.0 1762--> 1763 1764* `value` {any} 1765* Returns: {boolean} 1766 1767Returns `true` if the value is an iterator returned for a built-in 1768[`Set`][] instance. 1769 1770```js 1771const set = new Set(); 1772util.types.isSetIterator(set.keys()); // Returns true 1773util.types.isSetIterator(set.values()); // Returns true 1774util.types.isSetIterator(set.entries()); // Returns true 1775util.types.isSetIterator(set[Symbol.iterator]()); // Returns true 1776``` 1777 1778### `util.types.isSharedArrayBuffer(value)` 1779<!-- YAML 1780added: v10.0.0 1781--> 1782 1783* `value` {any} 1784* Returns: {boolean} 1785 1786Returns `true` if the value is a built-in [`SharedArrayBuffer`][] instance. 1787This does *not* include [`ArrayBuffer`][] instances. Usually, it is 1788desirable to test for both; See [`util.types.isAnyArrayBuffer()`][] for that. 1789 1790```js 1791util.types.isSharedArrayBuffer(new ArrayBuffer()); // Returns false 1792util.types.isSharedArrayBuffer(new SharedArrayBuffer()); // Returns true 1793``` 1794 1795### `util.types.isStringObject(value)` 1796<!-- YAML 1797added: v10.0.0 1798--> 1799 1800* `value` {any} 1801* Returns: {boolean} 1802 1803Returns `true` if the value is a string object, e.g. created 1804by `new String()`. 1805 1806```js 1807util.types.isStringObject('foo'); // Returns false 1808util.types.isStringObject(new String('foo')); // Returns true 1809``` 1810 1811### `util.types.isSymbolObject(value)` 1812<!-- YAML 1813added: v10.0.0 1814--> 1815 1816* `value` {any} 1817* Returns: {boolean} 1818 1819Returns `true` if the value is a symbol object, created 1820by calling `Object()` on a `Symbol` primitive. 1821 1822```js 1823const symbol = Symbol('foo'); 1824util.types.isSymbolObject(symbol); // Returns false 1825util.types.isSymbolObject(Object(symbol)); // Returns true 1826``` 1827 1828### `util.types.isTypedArray(value)` 1829<!-- YAML 1830added: v10.0.0 1831--> 1832 1833* `value` {any} 1834* Returns: {boolean} 1835 1836Returns `true` if the value is a built-in [`TypedArray`][] instance. 1837 1838```js 1839util.types.isTypedArray(new ArrayBuffer()); // Returns false 1840util.types.isTypedArray(new Uint8Array()); // Returns true 1841util.types.isTypedArray(new Float64Array()); // Returns true 1842``` 1843 1844See also [`ArrayBuffer.isView()`][]. 1845 1846### `util.types.isUint8Array(value)` 1847<!-- YAML 1848added: v10.0.0 1849--> 1850 1851* `value` {any} 1852* Returns: {boolean} 1853 1854Returns `true` if the value is a built-in [`Uint8Array`][] instance. 1855 1856```js 1857util.types.isUint8Array(new ArrayBuffer()); // Returns false 1858util.types.isUint8Array(new Uint8Array()); // Returns true 1859util.types.isUint8Array(new Float64Array()); // Returns false 1860``` 1861 1862### `util.types.isUint8ClampedArray(value)` 1863<!-- YAML 1864added: v10.0.0 1865--> 1866 1867* `value` {any} 1868* Returns: {boolean} 1869 1870Returns `true` if the value is a built-in [`Uint8ClampedArray`][] instance. 1871 1872```js 1873util.types.isUint8ClampedArray(new ArrayBuffer()); // Returns false 1874util.types.isUint8ClampedArray(new Uint8ClampedArray()); // Returns true 1875util.types.isUint8ClampedArray(new Float64Array()); // Returns false 1876``` 1877 1878### `util.types.isUint16Array(value)` 1879<!-- YAML 1880added: v10.0.0 1881--> 1882 1883* `value` {any} 1884* Returns: {boolean} 1885 1886Returns `true` if the value is a built-in [`Uint16Array`][] instance. 1887 1888```js 1889util.types.isUint16Array(new ArrayBuffer()); // Returns false 1890util.types.isUint16Array(new Uint16Array()); // Returns true 1891util.types.isUint16Array(new Float64Array()); // Returns false 1892``` 1893 1894### `util.types.isUint32Array(value)` 1895<!-- YAML 1896added: v10.0.0 1897--> 1898 1899* `value` {any} 1900* Returns: {boolean} 1901 1902Returns `true` if the value is a built-in [`Uint32Array`][] instance. 1903 1904```js 1905util.types.isUint32Array(new ArrayBuffer()); // Returns false 1906util.types.isUint32Array(new Uint32Array()); // Returns true 1907util.types.isUint32Array(new Float64Array()); // Returns false 1908``` 1909 1910### `util.types.isWeakMap(value)` 1911<!-- YAML 1912added: v10.0.0 1913--> 1914 1915* `value` {any} 1916* Returns: {boolean} 1917 1918Returns `true` if the value is a built-in [`WeakMap`][] instance. 1919 1920```js 1921util.types.isWeakMap(new WeakMap()); // Returns true 1922``` 1923 1924### `util.types.isWeakSet(value)` 1925<!-- YAML 1926added: v10.0.0 1927--> 1928 1929* `value` {any} 1930* Returns: {boolean} 1931 1932Returns `true` if the value is a built-in [`WeakSet`][] instance. 1933 1934```js 1935util.types.isWeakSet(new WeakSet()); // Returns true 1936``` 1937 1938### `util.types.isWebAssemblyCompiledModule(value)` 1939<!-- YAML 1940added: v10.0.0 1941--> 1942 1943* `value` {any} 1944* Returns: {boolean} 1945 1946Returns `true` if the value is a built-in [`WebAssembly.Module`][] instance. 1947 1948```js 1949const module = new WebAssembly.Module(wasmBuffer); 1950util.types.isWebAssemblyCompiledModule(module); // Returns true 1951``` 1952 1953## Deprecated APIs 1954 1955The following APIs are deprecated and should no longer be used. Existing 1956applications and modules should be updated to find alternative approaches. 1957 1958### `util._extend(target, source)` 1959<!-- YAML 1960added: v0.7.5 1961deprecated: v6.0.0 1962--> 1963 1964> Stability: 0 - Deprecated: Use [`Object.assign()`][] instead. 1965 1966* `target` {Object} 1967* `source` {Object} 1968 1969The `util._extend()` method was never intended to be used outside of internal 1970Node.js modules. The community found and used it anyway. 1971 1972It is deprecated and should not be used in new code. JavaScript comes with very 1973similar built-in functionality through [`Object.assign()`][]. 1974 1975### `util.isArray(object)` 1976<!-- YAML 1977added: v0.6.0 1978deprecated: v4.0.0 1979--> 1980 1981> Stability: 0 - Deprecated: Use [`Array.isArray()`][] instead. 1982 1983* `object` {any} 1984* Returns: {boolean} 1985 1986Alias for [`Array.isArray()`][]. 1987 1988Returns `true` if the given `object` is an `Array`. Otherwise, returns `false`. 1989 1990```js 1991const util = require('util'); 1992 1993util.isArray([]); 1994// Returns: true 1995util.isArray(new Array()); 1996// Returns: true 1997util.isArray({}); 1998// Returns: false 1999``` 2000 2001### `util.isBoolean(object)` 2002<!-- YAML 2003added: v0.11.5 2004deprecated: v4.0.0 2005--> 2006 2007> Stability: 0 - Deprecated: Use `typeof value === 'boolean'` instead. 2008 2009* `object` {any} 2010* Returns: {boolean} 2011 2012Returns `true` if the given `object` is a `Boolean`. Otherwise, returns `false`. 2013 2014```js 2015const util = require('util'); 2016 2017util.isBoolean(1); 2018// Returns: false 2019util.isBoolean(0); 2020// Returns: false 2021util.isBoolean(false); 2022// Returns: true 2023``` 2024 2025### `util.isBuffer(object)` 2026<!-- YAML 2027added: v0.11.5 2028deprecated: v4.0.0 2029--> 2030 2031> Stability: 0 - Deprecated: Use [`Buffer.isBuffer()`][] instead. 2032 2033* `object` {any} 2034* Returns: {boolean} 2035 2036Returns `true` if the given `object` is a `Buffer`. Otherwise, returns `false`. 2037 2038```js 2039const util = require('util'); 2040 2041util.isBuffer({ length: 0 }); 2042// Returns: false 2043util.isBuffer([]); 2044// Returns: false 2045util.isBuffer(Buffer.from('hello world')); 2046// Returns: true 2047``` 2048 2049### `util.isDate(object)` 2050<!-- YAML 2051added: v0.6.0 2052deprecated: v4.0.0 2053--> 2054 2055> Stability: 0 - Deprecated: Use [`util.types.isDate()`][] instead. 2056 2057* `object` {any} 2058* Returns: {boolean} 2059 2060Returns `true` if the given `object` is a `Date`. Otherwise, returns `false`. 2061 2062```js 2063const util = require('util'); 2064 2065util.isDate(new Date()); 2066// Returns: true 2067util.isDate(Date()); 2068// false (without 'new' returns a String) 2069util.isDate({}); 2070// Returns: false 2071``` 2072 2073### `util.isError(object)` 2074<!-- YAML 2075added: v0.6.0 2076deprecated: v4.0.0 2077--> 2078 2079> Stability: 0 - Deprecated: Use [`util.types.isNativeError()`][] instead. 2080 2081* `object` {any} 2082* Returns: {boolean} 2083 2084Returns `true` if the given `object` is an [`Error`][]. Otherwise, returns 2085`false`. 2086 2087```js 2088const util = require('util'); 2089 2090util.isError(new Error()); 2091// Returns: true 2092util.isError(new TypeError()); 2093// Returns: true 2094util.isError({ name: 'Error', message: 'an error occurred' }); 2095// Returns: false 2096``` 2097 2098This method relies on `Object.prototype.toString()` behavior. It is 2099possible to obtain an incorrect result when the `object` argument manipulates 2100`@@toStringTag`. 2101 2102```js 2103const util = require('util'); 2104const obj = { name: 'Error', message: 'an error occurred' }; 2105 2106util.isError(obj); 2107// Returns: false 2108obj[Symbol.toStringTag] = 'Error'; 2109util.isError(obj); 2110// Returns: true 2111``` 2112 2113### `util.isFunction(object)` 2114<!-- YAML 2115added: v0.11.5 2116deprecated: v4.0.0 2117--> 2118 2119> Stability: 0 - Deprecated: Use `typeof value === 'function'` instead. 2120 2121* `object` {any} 2122* Returns: {boolean} 2123 2124Returns `true` if the given `object` is a `Function`. Otherwise, returns 2125`false`. 2126 2127```js 2128const util = require('util'); 2129 2130function Foo() {} 2131const Bar = () => {}; 2132 2133util.isFunction({}); 2134// Returns: false 2135util.isFunction(Foo); 2136// Returns: true 2137util.isFunction(Bar); 2138// Returns: true 2139``` 2140 2141### `util.isNull(object)` 2142<!-- YAML 2143added: v0.11.5 2144deprecated: v4.0.0 2145--> 2146 2147> Stability: 0 - Deprecated: Use `value === null` instead. 2148 2149* `object` {any} 2150* Returns: {boolean} 2151 2152Returns `true` if the given `object` is strictly `null`. Otherwise, returns 2153`false`. 2154 2155```js 2156const util = require('util'); 2157 2158util.isNull(0); 2159// Returns: false 2160util.isNull(undefined); 2161// Returns: false 2162util.isNull(null); 2163// Returns: true 2164``` 2165 2166### `util.isNullOrUndefined(object)` 2167<!-- YAML 2168added: v0.11.5 2169deprecated: v4.0.0 2170--> 2171 2172> Stability: 0 - Deprecated: Use 2173> `value === undefined || value === null` instead. 2174 2175* `object` {any} 2176* Returns: {boolean} 2177 2178Returns `true` if the given `object` is `null` or `undefined`. Otherwise, 2179returns `false`. 2180 2181```js 2182const util = require('util'); 2183 2184util.isNullOrUndefined(0); 2185// Returns: false 2186util.isNullOrUndefined(undefined); 2187// Returns: true 2188util.isNullOrUndefined(null); 2189// Returns: true 2190``` 2191 2192### `util.isNumber(object)` 2193<!-- YAML 2194added: v0.11.5 2195deprecated: v4.0.0 2196--> 2197 2198> Stability: 0 - Deprecated: Use `typeof value === 'number'` instead. 2199 2200* `object` {any} 2201* Returns: {boolean} 2202 2203Returns `true` if the given `object` is a `Number`. Otherwise, returns `false`. 2204 2205```js 2206const util = require('util'); 2207 2208util.isNumber(false); 2209// Returns: false 2210util.isNumber(Infinity); 2211// Returns: true 2212util.isNumber(0); 2213// Returns: true 2214util.isNumber(NaN); 2215// Returns: true 2216``` 2217 2218### `util.isObject(object)` 2219<!-- YAML 2220added: v0.11.5 2221deprecated: v4.0.0 2222--> 2223 2224> Stability: 0 - Deprecated: 2225> Use `value !== null && typeof value === 'object'` instead. 2226 2227* `object` {any} 2228* Returns: {boolean} 2229 2230Returns `true` if the given `object` is strictly an `Object` **and** not a 2231`Function` (even though functions are objects in JavaScript). 2232Otherwise, returns `false`. 2233 2234```js 2235const util = require('util'); 2236 2237util.isObject(5); 2238// Returns: false 2239util.isObject(null); 2240// Returns: false 2241util.isObject({}); 2242// Returns: true 2243util.isObject(() => {}); 2244// Returns: false 2245``` 2246 2247### `util.isPrimitive(object)` 2248<!-- YAML 2249added: v0.11.5 2250deprecated: v4.0.0 2251--> 2252 2253> Stability: 0 - Deprecated: Use 2254> `(typeof value !== 'object' && typeof value !== 'function') || value === null` 2255> instead. 2256 2257* `object` {any} 2258* Returns: {boolean} 2259 2260Returns `true` if the given `object` is a primitive type. Otherwise, returns 2261`false`. 2262 2263```js 2264const util = require('util'); 2265 2266util.isPrimitive(5); 2267// Returns: true 2268util.isPrimitive('foo'); 2269// Returns: true 2270util.isPrimitive(false); 2271// Returns: true 2272util.isPrimitive(null); 2273// Returns: true 2274util.isPrimitive(undefined); 2275// Returns: true 2276util.isPrimitive({}); 2277// Returns: false 2278util.isPrimitive(() => {}); 2279// Returns: false 2280util.isPrimitive(/^$/); 2281// Returns: false 2282util.isPrimitive(new Date()); 2283// Returns: false 2284``` 2285 2286### `util.isRegExp(object)` 2287<!-- YAML 2288added: v0.6.0 2289deprecated: v4.0.0 2290--> 2291 2292> Stability: 0 - Deprecated 2293 2294* `object` {any} 2295* Returns: {boolean} 2296 2297Returns `true` if the given `object` is a `RegExp`. Otherwise, returns `false`. 2298 2299```js 2300const util = require('util'); 2301 2302util.isRegExp(/some regexp/); 2303// Returns: true 2304util.isRegExp(new RegExp('another regexp')); 2305// Returns: true 2306util.isRegExp({}); 2307// Returns: false 2308``` 2309 2310### `util.isString(object)` 2311<!-- YAML 2312added: v0.11.5 2313deprecated: v4.0.0 2314--> 2315 2316> Stability: 0 - Deprecated: Use `typeof value === 'string'` instead. 2317 2318* `object` {any} 2319* Returns: {boolean} 2320 2321Returns `true` if the given `object` is a `string`. Otherwise, returns `false`. 2322 2323```js 2324const util = require('util'); 2325 2326util.isString(''); 2327// Returns: true 2328util.isString('foo'); 2329// Returns: true 2330util.isString(String('foo')); 2331// Returns: true 2332util.isString(5); 2333// Returns: false 2334``` 2335 2336### `util.isSymbol(object)` 2337<!-- YAML 2338added: v0.11.5 2339deprecated: v4.0.0 2340--> 2341 2342> Stability: 0 - Deprecated: Use `typeof value === 'symbol'` instead. 2343 2344* `object` {any} 2345* Returns: {boolean} 2346 2347Returns `true` if the given `object` is a `Symbol`. Otherwise, returns `false`. 2348 2349```js 2350const util = require('util'); 2351 2352util.isSymbol(5); 2353// Returns: false 2354util.isSymbol('foo'); 2355// Returns: false 2356util.isSymbol(Symbol('foo')); 2357// Returns: true 2358``` 2359 2360### `util.isUndefined(object)` 2361<!-- YAML 2362added: v0.11.5 2363deprecated: v4.0.0 2364--> 2365 2366> Stability: 0 - Deprecated: Use `value === undefined` instead. 2367 2368* `object` {any} 2369* Returns: {boolean} 2370 2371Returns `true` if the given `object` is `undefined`. Otherwise, returns `false`. 2372 2373```js 2374const util = require('util'); 2375 2376const foo = undefined; 2377util.isUndefined(5); 2378// Returns: false 2379util.isUndefined(foo); 2380// Returns: true 2381util.isUndefined(null); 2382// Returns: false 2383``` 2384 2385### `util.log(string)` 2386<!-- YAML 2387added: v0.3.0 2388deprecated: v6.0.0 2389--> 2390 2391> Stability: 0 - Deprecated: Use a third party module instead. 2392 2393* `string` {string} 2394 2395The `util.log()` method prints the given `string` to `stdout` with an included 2396timestamp. 2397 2398```js 2399const util = require('util'); 2400 2401util.log('Timestamped message.'); 2402``` 2403 2404[`'uncaughtException'`]: process.html#process_event_uncaughtexception 2405[`'warning'`]: process.html#process_event_warning 2406[`Array.isArray()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray 2407[`ArrayBuffer.isView()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView 2408[`ArrayBuffer`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer 2409[`Buffer.isBuffer()`]: buffer.html#buffer_static_method_buffer_isbuffer_obj 2410[`DataView`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView 2411[`Date`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date 2412[`Error`]: errors.html#errors_class_error 2413[`Float32Array`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array 2414[`Float64Array`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array 2415[`Int16Array`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array 2416[`Int32Array`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array 2417[`Int8Array`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array 2418[`Map`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map 2419[`Object.assign()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign 2420[`Object.freeze()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze 2421[`Promise`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise 2422[`Proxy`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy 2423[`Set`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set 2424[`SharedArrayBuffer`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer 2425[`TypedArray`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray 2426[`Uint16Array`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array 2427[`Uint32Array`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array 2428[`Uint8Array`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array 2429[`Uint8ClampedArray`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray 2430[`WeakMap`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap 2431[`WeakSet`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet 2432[`WebAssembly.Module`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module 2433[`assert.deepStrictEqual()`]: assert.html#assert_assert_deepstrictequal_actual_expected_message 2434[`console.error()`]: console.html#console_console_error_data_args 2435[`target` and `handler`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#Terminology 2436[`tty.hasColors()`]: tty.html#tty_writestream_hascolors_count_env 2437[`util.format()`]: #util_util_format_format_args 2438[`util.inspect()`]: #util_util_inspect_object_options 2439[`util.promisify()`]: #util_util_promisify_original 2440[`util.types.isAnyArrayBuffer()`]: #util_util_types_isanyarraybuffer_value 2441[`util.types.isArrayBuffer()`]: #util_util_types_isarraybuffer_value 2442[`util.types.isDate()`]: #util_util_types_isdate_value 2443[`util.types.isNativeError()`]: #util_util_types_isnativeerror_value 2444[`util.types.isSharedArrayBuffer()`]: #util_util_types_issharedarraybuffer_value 2445[Common System Errors]: errors.html#errors_common_system_errors 2446[Custom inspection functions on objects]: #util_custom_inspection_functions_on_objects 2447[Custom promisified functions]: #util_custom_promisified_functions 2448[Customizing `util.inspect` colors]: #util_customizing_util_inspect_colors 2449[Internationalization]: intl.html 2450[Module Namespace Object]: https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects 2451[WHATWG Encoding Standard]: https://encoding.spec.whatwg.org/ 2452[async function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function 2453[compare function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Parameters 2454[constructor]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor 2455[default sort]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort 2456[global symbol registry]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/for 2457[list of deprecated APIS]: deprecations.html#deprecations_list_of_deprecated_apis 2458[`napi_create_external()`]: n-api.html#n_api_napi_create_external 2459[semantically incompatible]: https://github.com/nodejs/node/issues/4179 2460[util.inspect.custom]: #util_util_inspect_custom 2461