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