• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Util
2
3<!--introduced_in=v0.10.0-->
4
5> Stability: 2 - Stable
6
7<!-- source_link=lib/util.js -->
8
9The `node: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('node:util');
15```
16
17## `util.callbackify(original)`
18
19<!-- YAML
20added: v8.2.0
21-->
22
23* `original` {Function} An `async` function
24* Returns: {Function} a callback style function
25
26Takes an `async` function (or a function that returns a `Promise`) and returns a
27function following the error-first callback style, i.e. taking
28an `(err, value) => ...` callback as the last argument. In the callback, the
29first argument will be the rejection reason (or `null` if the `Promise`
30resolved), and the second argument will be the resolved value.
31
32```js
33const util = require('node:util');
34
35async function fn() {
36  return 'hello world';
37}
38const callbackFunction = util.callbackify(fn);
39
40callbackFunction((err, ret) => {
41  if (err) throw err;
42  console.log(ret);
43});
44```
45
46Will print:
47
48```text
49hello world
50```
51
52The callback is executed asynchronously, and will have a limited stack trace.
53If the callback throws, the process will emit an [`'uncaughtException'`][]
54event, and if not handled will exit.
55
56Since `null` has a special meaning as the first argument to a callback, if a
57wrapped function rejects a `Promise` with a falsy value as a reason, the value
58is wrapped in an `Error` with the original value stored in a field named
59`reason`.
60
61```js
62function fn() {
63  return Promise.reject(null);
64}
65const callbackFunction = util.callbackify(fn);
66
67callbackFunction((err, ret) => {
68  // When the Promise was rejected with `null` it is wrapped with an Error and
69  // the original value is stored in `reason`.
70  err && Object.hasOwn(err, 'reason') && err.reason === null;  // true
71});
72```
73
74## `util.debuglog(section[, callback])`
75
76<!-- YAML
77added: v0.11.3
78-->
79
80* `section` {string} A string identifying the portion of the application for
81  which the `debuglog` function is being created.
82* `callback` {Function} A callback invoked the first time the logging function
83  is called with a function argument that is a more optimized logging function.
84* Returns: {Function} The logging function
85
86The `util.debuglog()` method is used to create a function that conditionally
87writes debug messages to `stderr` based on the existence of the `NODE_DEBUG`
88environment variable. If the `section` name appears within the value of that
89environment variable, then the returned function operates similar to
90[`console.error()`][]. If not, then the returned function is a no-op.
91
92```js
93const util = require('node:util');
94const debuglog = util.debuglog('foo');
95
96debuglog('hello from foo [%d]', 123);
97```
98
99If this program is run with `NODE_DEBUG=foo` in the environment, then
100it will output something like:
101
102```console
103FOO 3245: hello from foo [123]
104```
105
106where `3245` is the process id. If it is not run with that
107environment variable set, then it will not print anything.
108
109The `section` supports wildcard also:
110
111```js
112const util = require('node:util');
113const debuglog = util.debuglog('foo-bar');
114
115debuglog('hi there, it\'s foo-bar [%d]', 2333);
116```
117
118if it is run with `NODE_DEBUG=foo*` in the environment, then it will output
119something like:
120
121```console
122FOO-BAR 3257: hi there, it's foo-bar [2333]
123```
124
125Multiple comma-separated `section` names may be specified in the `NODE_DEBUG`
126environment variable: `NODE_DEBUG=fs,net,tls`.
127
128The optional `callback` argument can be used to replace the logging function
129with a different function that doesn't have any initialization or
130unnecessary wrapping.
131
132```js
133const util = require('node:util');
134let debuglog = util.debuglog('internals', (debug) => {
135  // Replace with a logging function that optimizes out
136  // testing if the section is enabled
137  debuglog = debug;
138});
139```
140
141### `debuglog().enabled`
142
143<!-- YAML
144added: v14.9.0
145-->
146
147* {boolean}
148
149The `util.debuglog().enabled` getter is used to create a test that can be used
150in conditionals based on the existence of the `NODE_DEBUG` environment variable.
151If the `section` name appears within the value of that environment variable,
152then the returned value will be `true`. If not, then the returned value will be
153`false`.
154
155```js
156const util = require('node:util');
157const enabled = util.debuglog('foo').enabled;
158if (enabled) {
159  console.log('hello from foo [%d]', 123);
160}
161```
162
163If this program is run with `NODE_DEBUG=foo` in the environment, then it will
164output something like:
165
166```console
167hello from foo [123]
168```
169
170## `util.debug(section)`
171
172<!-- YAML
173added: v14.9.0
174-->
175
176Alias for `util.debuglog`. Usage allows for readability of that doesn't imply
177logging when only using `util.debuglog().enabled`.
178
179## `util.deprecate(fn, msg[, code])`
180
181<!-- YAML
182added: v0.8.0
183changes:
184  - version: v10.0.0
185    pr-url: https://github.com/nodejs/node/pull/16393
186    description: Deprecation warnings are only emitted once for each code.
187-->
188
189* `fn` {Function} The function that is being deprecated.
190* `msg` {string} A warning message to display when the deprecated function is
191  invoked.
192* `code` {string} A deprecation code. See the [list of deprecated APIs][] for a
193  list of codes.
194* Returns: {Function} The deprecated function wrapped to emit a warning.
195
196The `util.deprecate()` method wraps `fn` (which may be a function or class) in
197such a way that it is marked as deprecated.
198
199```js
200const util = require('node:util');
201
202exports.obsoleteFunction = util.deprecate(() => {
203  // Do something here.
204}, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.');
205```
206
207When called, `util.deprecate()` will return a function that will emit a
208`DeprecationWarning` using the [`'warning'`][] event. The warning will
209be emitted and printed to `stderr` the first time the returned function is
210called. After the warning is emitted, the wrapped function is called without
211emitting a warning.
212
213If the same optional `code` is supplied in multiple calls to `util.deprecate()`,
214the warning will be emitted only once for that `code`.
215
216```js
217const util = require('node:util');
218
219const fn1 = util.deprecate(someFunction, someMessage, 'DEP0001');
220const fn2 = util.deprecate(someOtherFunction, someOtherMessage, 'DEP0001');
221fn1(); // Emits a deprecation warning with code DEP0001
222fn2(); // Does not emit a deprecation warning because it has the same code
223```
224
225If either the `--no-deprecation` or `--no-warnings` command-line flags are
226used, or if the `process.noDeprecation` property is set to `true` _prior_ to
227the first deprecation warning, the `util.deprecate()` method does nothing.
228
229If the `--trace-deprecation` or `--trace-warnings` command-line flags are set,
230or the `process.traceDeprecation` property is set to `true`, a warning and a
231stack trace are printed to `stderr` the first time the deprecated function is
232called.
233
234If the `--throw-deprecation` command-line flag is set, or the
235`process.throwDeprecation` property is set to `true`, then an exception will be
236thrown when the deprecated function is called.
237
238The `--throw-deprecation` command-line flag and `process.throwDeprecation`
239property take precedence over `--trace-deprecation` and
240`process.traceDeprecation`.
241
242## `util.format(format[, ...args])`
243
244<!-- YAML
245added: v0.5.3
246changes:
247  - version: v12.11.0
248    pr-url: https://github.com/nodejs/node/pull/29606
249    description: The `%c` specifier is ignored now.
250  - version: v12.0.0
251    pr-url: https://github.com/nodejs/node/pull/23162
252    description: The `format` argument is now only taken as such if it actually
253                 contains format specifiers.
254  - version: v12.0.0
255    pr-url: https://github.com/nodejs/node/pull/23162
256    description: If the `format` argument is not a format string, the output
257                 string's formatting is no longer dependent on the type of the
258                 first argument. This change removes previously present quotes
259                 from strings that were being output when the first argument
260                 was not a string.
261  - version: v11.4.0
262    pr-url: https://github.com/nodejs/node/pull/23708
263    description: The `%d`, `%f`, and `%i` specifiers now support Symbols
264                 properly.
265  - version: v11.4.0
266    pr-url: https://github.com/nodejs/node/pull/24806
267    description: The `%o` specifier's `depth` has default depth of 4 again.
268  - version: v11.0.0
269    pr-url: https://github.com/nodejs/node/pull/17907
270    description: The `%o` specifier's `depth` option will now fall back to the
271                 default depth.
272  - version: v10.12.0
273    pr-url: https://github.com/nodejs/node/pull/22097
274    description: The `%d` and `%i` specifiers now support BigInt.
275  - version: v8.4.0
276    pr-url: https://github.com/nodejs/node/pull/14558
277    description: The `%o` and `%O` specifiers are supported now.
278-->
279
280* `format` {string} A `printf`-like format string.
281
282The `util.format()` method returns a formatted string using the first argument
283as a `printf`-like format string which can contain zero or more format
284specifiers. Each specifier is replaced with the converted value from the
285corresponding argument. Supported specifiers are:
286
287* `%s`: `String` will be used to convert all values except `BigInt`, `Object`
288  and `-0`. `BigInt` values will be represented with an `n` and Objects that
289  have no user defined `toString` function are inspected using `util.inspect()`
290  with options `{ depth: 0, colors: false, compact: 3 }`.
291* `%d`: `Number` will be used to convert all values except `BigInt` and
292  `Symbol`.
293* `%i`: `parseInt(value, 10)` is used for all values except `BigInt` and
294  `Symbol`.
295* `%f`: `parseFloat(value)` is used for all values expect `Symbol`.
296* `%j`: JSON. Replaced with the string `'[Circular]'` if the argument contains
297  circular references.
298* `%o`: `Object`. A string representation of an object with generic JavaScript
299  object formatting. Similar to `util.inspect()` with options
300  `{ showHidden: true, showProxy: true }`. This will show the full object
301  including non-enumerable properties and proxies.
302* `%O`: `Object`. A string representation of an object with generic JavaScript
303  object formatting. Similar to `util.inspect()` without options. This will show
304  the full object not including non-enumerable properties and proxies.
305* `%c`: `CSS`. This specifier is ignored and will skip any CSS passed in.
306* `%%`: single percent sign (`'%'`). This does not consume an argument.
307* Returns: {string} The formatted string
308
309If a specifier does not have a corresponding argument, it is not replaced:
310
311```js
312util.format('%s:%s', 'foo');
313// Returns: 'foo:%s'
314```
315
316Values that are not part of the format string are formatted using
317`util.inspect()` if their type is not `string`.
318
319If there are more arguments passed to the `util.format()` method than the
320number of specifiers, the extra arguments are concatenated to the returned
321string, separated by spaces:
322
323```js
324util.format('%s:%s', 'foo', 'bar', 'baz');
325// Returns: 'foo:bar baz'
326```
327
328If the first argument does not contain a valid format specifier, `util.format()`
329returns a string that is the concatenation of all arguments separated by spaces:
330
331```js
332util.format(1, 2, 3);
333// Returns: '1 2 3'
334```
335
336If only one argument is passed to `util.format()`, it is returned as it is
337without any formatting:
338
339```js
340util.format('%% %s');
341// Returns: '%% %s'
342```
343
344`util.format()` is a synchronous method that is intended as a debugging tool.
345Some input values can have a significant performance overhead that can block the
346event loop. Use this function with care and never in a hot code path.
347
348## `util.formatWithOptions(inspectOptions, format[, ...args])`
349
350<!-- YAML
351added: v10.0.0
352-->
353
354* `inspectOptions` {Object}
355* `format` {string}
356
357This function is identical to [`util.format()`][], except in that it takes
358an `inspectOptions` argument which specifies options that are passed along to
359[`util.inspect()`][].
360
361```js
362util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 });
363// Returns 'See object { foo: 42 }', where `42` is colored as a number
364// when printed to a terminal.
365```
366
367## `util.getSystemErrorName(err)`
368
369<!-- YAML
370added: v9.7.0
371-->
372
373* `err` {number}
374* Returns: {string}
375
376Returns the string name for a numeric error code that comes from a Node.js API.
377The mapping between error codes and error names is platform-dependent.
378See [Common System Errors][] for the names of common errors.
379
380```js
381fs.access('file/that/does/not/exist', (err) => {
382  const name = util.getSystemErrorName(err.errno);
383  console.error(name);  // ENOENT
384});
385```
386
387## `util.getSystemErrorMap()`
388
389<!-- YAML
390added:
391  - v16.0.0
392  - v14.17.0
393-->
394
395* Returns: {Map}
396
397Returns a Map of all system error codes available from the Node.js API.
398The mapping between error codes and error names is platform-dependent.
399See [Common System Errors][] for the names of common errors.
400
401```js
402fs.access('file/that/does/not/exist', (err) => {
403  const errorMap = util.getSystemErrorMap();
404  const name = errorMap.get(err.errno);
405  console.error(name);  // ENOENT
406});
407```
408
409## `util.inherits(constructor, superConstructor)`
410
411<!-- YAML
412added: v0.3.0
413changes:
414  - version: v5.0.0
415    pr-url: https://github.com/nodejs/node/pull/3455
416    description: The `constructor` parameter can refer to an ES6 class now.
417-->
418
419> Stability: 3 - Legacy: Use ES2015 class syntax and `extends` keyword instead.
420
421* `constructor` {Function}
422* `superConstructor` {Function}
423
424Usage of `util.inherits()` is discouraged. Please use the ES6 `class` and
425`extends` keywords to get language level inheritance support. Also note
426that the two styles are [semantically incompatible][].
427
428Inherit the prototype methods from one [constructor][] into another. The
429prototype of `constructor` will be set to a new object created from
430`superConstructor`.
431
432This mainly adds some input validation on top of
433`Object.setPrototypeOf(constructor.prototype, superConstructor.prototype)`.
434As an additional convenience, `superConstructor` will be accessible
435through the `constructor.super_` property.
436
437```js
438const util = require('node:util');
439const EventEmitter = require('node:events');
440
441function MyStream() {
442  EventEmitter.call(this);
443}
444
445util.inherits(MyStream, EventEmitter);
446
447MyStream.prototype.write = function(data) {
448  this.emit('data', data);
449};
450
451const stream = new MyStream();
452
453console.log(stream instanceof EventEmitter); // true
454console.log(MyStream.super_ === EventEmitter); // true
455
456stream.on('data', (data) => {
457  console.log(`Received data: "${data}"`);
458});
459stream.write('It works!'); // Received data: "It works!"
460```
461
462ES6 example using `class` and `extends`:
463
464```js
465const EventEmitter = require('node:events');
466
467class MyStream extends EventEmitter {
468  write(data) {
469    this.emit('data', data);
470  }
471}
472
473const stream = new MyStream();
474
475stream.on('data', (data) => {
476  console.log(`Received data: "${data}"`);
477});
478stream.write('With ES6');
479```
480
481## `util.inspect(object[, options])`
482
483## `util.inspect(object[, showHidden[, depth[, colors]]])`
484
485<!-- YAML
486added: v0.3.0
487changes:
488  - version:
489    - v17.3.0
490    - v16.14.0
491    pr-url: https://github.com/nodejs/node/pull/41003
492    description: The `numericSeparator` option is supported now.
493  - version:
494    - v14.6.0
495    - v12.19.0
496    pr-url: https://github.com/nodejs/node/pull/33690
497    description: If `object` is from a different `vm.Context` now, a custom
498                 inspection function on it will not receive context-specific
499                 arguments anymore.
500  - version:
501     - v13.13.0
502     - v12.17.0
503    pr-url: https://github.com/nodejs/node/pull/32392
504    description: The `maxStringLength` option is supported now.
505  - version:
506     - v13.5.0
507     - v12.16.0
508    pr-url: https://github.com/nodejs/node/pull/30768
509    description: User defined prototype properties are inspected in case
510                 `showHidden` is `true`.
511  - version: v13.0.0
512    pr-url: https://github.com/nodejs/node/pull/27685
513    description: Circular references now include a marker to the reference.
514  - version: v12.0.0
515    pr-url: https://github.com/nodejs/node/pull/27109
516    description: The `compact` options default is changed to `3` and the
517                 `breakLength` options default is changed to `80`.
518  - version: v12.0.0
519    pr-url: https://github.com/nodejs/node/pull/24971
520    description: Internal properties no longer appear in the context argument
521                 of a custom inspection function.
522  - version: v11.11.0
523    pr-url: https://github.com/nodejs/node/pull/26269
524    description: The `compact` option accepts numbers for a new output mode.
525  - version: v11.7.0
526    pr-url: https://github.com/nodejs/node/pull/25006
527    description: ArrayBuffers now also show their binary contents.
528  - version: v11.5.0
529    pr-url: https://github.com/nodejs/node/pull/24852
530    description: The `getters` option is supported now.
531  - version: v11.4.0
532    pr-url: https://github.com/nodejs/node/pull/24326
533    description: The `depth` default changed back to `2`.
534  - version: v11.0.0
535    pr-url: https://github.com/nodejs/node/pull/22846
536    description: The `depth` default changed to `20`.
537  - version: v11.0.0
538    pr-url: https://github.com/nodejs/node/pull/22756
539    description: The inspection output is now limited to about 128 MiB. Data
540                 above that size will not be fully inspected.
541  - version: v10.12.0
542    pr-url: https://github.com/nodejs/node/pull/22788
543    description: The `sorted` option is supported now.
544  - version: v10.6.0
545    pr-url: https://github.com/nodejs/node/pull/20725
546    description: Inspecting linked lists and similar objects is now possible
547                 up to the maximum call stack size.
548  - version: v10.0.0
549    pr-url: https://github.com/nodejs/node/pull/19259
550    description: The `WeakMap` and `WeakSet` entries can now be inspected
551                 as well.
552  - version: v9.9.0
553    pr-url: https://github.com/nodejs/node/pull/17576
554    description: The `compact` option is supported now.
555  - version: v6.6.0
556    pr-url: https://github.com/nodejs/node/pull/8174
557    description: Custom inspection functions can now return `this`.
558  - version: v6.3.0
559    pr-url: https://github.com/nodejs/node/pull/7499
560    description: The `breakLength` option is supported now.
561  - version: v6.1.0
562    pr-url: https://github.com/nodejs/node/pull/6334
563    description: The `maxArrayLength` option is supported now; in particular,
564                 long arrays are truncated by default.
565  - version: v6.1.0
566    pr-url: https://github.com/nodejs/node/pull/6465
567    description: The `showProxy` option is supported now.
568-->
569
570* `object` {any} Any JavaScript primitive or `Object`.
571* `options` {Object}
572  * `showHidden` {boolean} If `true`, `object`'s non-enumerable symbols and
573    properties are included in the formatted result. [`WeakMap`][] and
574    [`WeakSet`][] entries are also included as well as user defined prototype
575    properties (excluding method properties). **Default:** `false`.
576  * `depth` {number} Specifies the number of times to recurse while formatting
577    `object`. This is useful for inspecting large objects. To recurse up to
578    the maximum call stack size pass `Infinity` or `null`.
579    **Default:** `2`.
580  * `colors` {boolean} If `true`, the output is styled with ANSI color
581    codes. Colors are customizable. See [Customizing `util.inspect` colors][].
582    **Default:** `false`.
583  * `customInspect` {boolean} If `false`,
584    `[util.inspect.custom](depth, opts, inspect)` functions are not invoked.
585    **Default:** `true`.
586  * `showProxy` {boolean} If `true`, `Proxy` inspection includes
587    the [`target` and `handler`][] objects. **Default:** `false`.
588  * `maxArrayLength` {integer} Specifies the maximum number of `Array`,
589    [`TypedArray`][], [`WeakMap`][], and [`WeakSet`][] elements to include when
590    formatting. Set to `null` or `Infinity` to show all elements. Set to `0` or
591    negative to show no elements. **Default:** `100`.
592  * `maxStringLength` {integer} Specifies the maximum number of characters to
593    include when formatting. Set to `null` or `Infinity` to show all elements.
594    Set to `0` or negative to show no characters. **Default:** `10000`.
595  * `breakLength` {integer} The length at which input values are split across
596    multiple lines. Set to `Infinity` to format the input as a single line
597    (in combination with `compact` set to `true` or any number >= `1`).
598    **Default:** `80`.
599  * `compact` {boolean|integer} Setting this to `false` causes each object key
600    to be displayed on a new line. It will break on new lines in text that is
601    longer than `breakLength`. If set to a number, the most `n` inner elements
602    are united on a single line as long as all properties fit into
603    `breakLength`. Short array elements are also grouped together. For more
604    information, see the example below. **Default:** `3`.
605  * `sorted` {boolean|Function} If set to `true` or a function, all properties
606    of an object, and `Set` and `Map` entries are sorted in the resulting
607    string. If set to `true` the [default sort][] is used. If set to a function,
608    it is used as a [compare function][].
609  * `getters` {boolean|string} If set to `true`, getters are inspected. If set
610    to `'get'`, only getters without a corresponding setter are inspected. If
611    set to `'set'`, only getters with a corresponding setter are inspected.
612    This might cause side effects depending on the getter function.
613    **Default:** `false`.
614  * `numericSeparator` {boolean} If set to `true`, an underscore is used to
615    separate every three digits in all bigints and numbers.
616    **Default:** `false`.
617* Returns: {string} The representation of `object`.
618
619The `util.inspect()` method returns a string representation of `object` that is
620intended for debugging. The output of `util.inspect` may change at any time
621and should not be depended upon programmatically. Additional `options` may be
622passed that alter the result.
623`util.inspect()` will use the constructor's name and/or `@@toStringTag` to make
624an identifiable tag for an inspected value.
625
626```js
627class Foo {
628  get [Symbol.toStringTag]() {
629    return 'bar';
630  }
631}
632
633class Bar {}
634
635const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } });
636
637util.inspect(new Foo()); // 'Foo [bar] {}'
638util.inspect(new Bar()); // 'Bar {}'
639util.inspect(baz);       // '[foo] {}'
640```
641
642Circular references point to their anchor by using a reference index:
643
644```js
645const { inspect } = require('node:util');
646
647const obj = {};
648obj.a = [obj];
649obj.b = {};
650obj.b.inner = obj.b;
651obj.b.obj = obj;
652
653console.log(inspect(obj));
654// <ref *1> {
655//   a: [ [Circular *1] ],
656//   b: <ref *2> { inner: [Circular *2], obj: [Circular *1] }
657// }
658```
659
660The following example inspects all properties of the `util` object:
661
662```js
663const util = require('node:util');
664
665console.log(util.inspect(util, { showHidden: true, depth: null }));
666```
667
668The following example highlights the effect of the `compact` option:
669
670```js
671const util = require('node:util');
672
673const o = {
674  a: [1, 2, [[
675    'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do ' +
676      'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.',
677    'test',
678    'foo']], 4],
679  b: new Map([['za', 1], ['zb', 'test']]),
680};
681console.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 }));
682
683// { a:
684//   [ 1,
685//     2,
686//     [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // A long line
687//           'test',
688//           'foo' ] ],
689//     4 ],
690//   b: Map(2) { 'za' => 1, 'zb' => 'test' } }
691
692// Setting `compact` to false or an integer creates more reader friendly output.
693console.log(util.inspect(o, { compact: false, depth: 5, breakLength: 80 }));
694
695// {
696//   a: [
697//     1,
698//     2,
699//     [
700//       [
701//         'Lorem ipsum dolor sit amet,\n' +
702//           'consectetur adipiscing elit, sed do eiusmod \n' +
703//           'tempor incididunt ut labore et dolore magna aliqua.',
704//         'test',
705//         'foo'
706//       ]
707//     ],
708//     4
709//   ],
710//   b: Map(2) {
711//     'za' => 1,
712//     'zb' => 'test'
713//   }
714// }
715
716// Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a
717// single line.
718```
719
720The `showHidden` option allows [`WeakMap`][] and [`WeakSet`][] entries to be
721inspected. If there are more entries than `maxArrayLength`, there is no
722guarantee which entries are displayed. That means retrieving the same
723[`WeakSet`][] entries twice may result in different output. Furthermore, entries
724with no remaining strong references may be garbage collected at any time.
725
726```js
727const { inspect } = require('node:util');
728
729const obj = { a: 1 };
730const obj2 = { b: 2 };
731const weakSet = new WeakSet([obj, obj2]);
732
733console.log(inspect(weakSet, { showHidden: true }));
734// WeakSet { { a: 1 }, { b: 2 } }
735```
736
737The `sorted` option ensures that an object's property insertion order does not
738impact the result of `util.inspect()`.
739
740```js
741const { inspect } = require('node:util');
742const assert = require('node:assert');
743
744const o1 = {
745  b: [2, 3, 1],
746  a: '`a` comes before `b`',
747  c: new Set([2, 3, 1]),
748};
749console.log(inspect(o1, { sorted: true }));
750// { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } }
751console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) }));
752// { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' }
753
754const o2 = {
755  c: new Set([2, 1, 3]),
756  a: '`a` comes before `b`',
757  b: [2, 3, 1],
758};
759assert.strict.equal(
760  inspect(o1, { sorted: true }),
761  inspect(o2, { sorted: true }),
762);
763```
764
765The `numericSeparator` option adds an underscore every three digits to all
766numbers.
767
768```js
769const { inspect } = require('node:util');
770
771const thousand = 1_000;
772const million = 1_000_000;
773const bigNumber = 123_456_789n;
774const bigDecimal = 1_234.123_45;
775
776console.log(thousand, million, bigNumber, bigDecimal);
777// 1_000 1_000_000 123_456_789n 1_234.123_45
778```
779
780`util.inspect()` is a synchronous method intended for debugging. Its maximum
781output length is approximately 128 MiB. Inputs that result in longer output will
782be truncated.
783
784### Customizing `util.inspect` colors
785
786<!-- type=misc -->
787
788Color output (if enabled) of `util.inspect` is customizable globally
789via the `util.inspect.styles` and `util.inspect.colors` properties.
790
791`util.inspect.styles` is a map associating a style name to a color from
792`util.inspect.colors`.
793
794The default styles and associated colors are:
795
796* `bigint`: `yellow`
797* `boolean`: `yellow`
798* `date`: `magenta`
799* `module`: `underline`
800* `name`: (no styling)
801* `null`: `bold`
802* `number`: `yellow`
803* `regexp`: `red`
804* `special`: `cyan` (e.g., `Proxies`)
805* `string`: `green`
806* `symbol`: `green`
807* `undefined`: `grey`
808
809Color styling uses ANSI control codes that may not be supported on all
810terminals. To verify color support use [`tty.hasColors()`][].
811
812Predefined control codes are listed below (grouped as "Modifiers", "Foreground
813colors", and "Background colors").
814
815#### Modifiers
816
817Modifier support varies throughout different terminals. They will mostly be
818ignored, if not supported.
819
820* `reset` - Resets all (color) modifiers to their defaults
821* **bold** - Make text bold
822* _italic_ - Make text italic
823* <span style="border-bottom: 1px;">underline</span> - Make text underlined
824* ~~strikethrough~~ - Puts a horizontal line through the center of the text
825  (Alias: `strikeThrough`, `crossedout`, `crossedOut`)
826* `hidden` - Prints the text, but makes it invisible (Alias: conceal)
827* <span style="opacity: 0.5;">dim</span> - Decreased color intensity (Alias:
828  `faint`)
829* <span style="border-top: 1px">overlined</span> - Make text overlined
830* blink - Hides and shows the text in an interval
831* <span style="filter: invert(100%)">inverse</span> - Swap foreground and
832  background colors (Alias: `swapcolors`, `swapColors`)
833* <span style="border-bottom: 1px double;">doubleunderline</span> - Make text
834  double underlined (Alias: `doubleUnderline`)
835* <span style="border: 1px">framed</span> - Draw a frame around the text
836
837#### Foreground colors
838
839* `black`
840* `red`
841* `green`
842* `yellow`
843* `blue`
844* `magenta`
845* `cyan`
846* `white`
847* `gray` (alias: `grey`, `blackBright`)
848* `redBright`
849* `greenBright`
850* `yellowBright`
851* `blueBright`
852* `magentaBright`
853* `cyanBright`
854* `whiteBright`
855
856#### Background colors
857
858* `bgBlack`
859* `bgRed`
860* `bgGreen`
861* `bgYellow`
862* `bgBlue`
863* `bgMagenta`
864* `bgCyan`
865* `bgWhite`
866* `bgGray` (alias: `bgGrey`, `bgBlackBright`)
867* `bgRedBright`
868* `bgGreenBright`
869* `bgYellowBright`
870* `bgBlueBright`
871* `bgMagentaBright`
872* `bgCyanBright`
873* `bgWhiteBright`
874
875### Custom inspection functions on objects
876
877<!-- type=misc -->
878
879<!-- YAML
880added: v0.1.97
881changes:
882  - version:
883      - v17.3.0
884      - v16.14.0
885    pr-url: https://github.com/nodejs/node/pull/41019
886    description: The inspect argument is added for more interoperability.
887-->
888
889Objects may also define their own
890[`[util.inspect.custom](depth, opts, inspect)`][util.inspect.custom] function,
891which `util.inspect()` will invoke and use the result of when inspecting
892the object.
893
894```js
895const util = require('node:util');
896
897class Box {
898  constructor(value) {
899    this.value = value;
900  }
901
902  [util.inspect.custom](depth, options, inspect) {
903    if (depth < 0) {
904      return options.stylize('[Box]', 'special');
905    }
906
907    const newOptions = Object.assign({}, options, {
908      depth: options.depth === null ? null : options.depth - 1,
909    });
910
911    // Five space padding because that's the size of "Box< ".
912    const padding = ' '.repeat(5);
913    const inner = inspect(this.value, newOptions)
914                  .replace(/\n/g, `\n${padding}`);
915    return `${options.stylize('Box', 'special')}< ${inner} >`;
916  }
917}
918
919const box = new Box(true);
920
921util.inspect(box);
922// Returns: "Box< true >"
923```
924
925Custom `[util.inspect.custom](depth, opts, inspect)` functions typically return
926a string but may return a value of any type that will be formatted accordingly
927by `util.inspect()`.
928
929```js
930const util = require('node:util');
931
932const obj = { foo: 'this will not show up in the inspect() output' };
933obj[util.inspect.custom] = (depth) => {
934  return { bar: 'baz' };
935};
936
937util.inspect(obj);
938// Returns: "{ bar: 'baz' }"
939```
940
941### `util.inspect.custom`
942
943<!-- YAML
944added: v6.6.0
945changes:
946  - version: v10.12.0
947    pr-url: https://github.com/nodejs/node/pull/20857
948    description: This is now defined as a shared symbol.
949-->
950
951* {symbol} that can be used to declare custom inspect functions.
952
953In addition to being accessible through `util.inspect.custom`, this
954symbol is [registered globally][global symbol registry] and can be
955accessed in any environment as `Symbol.for('nodejs.util.inspect.custom')`.
956
957Using this allows code to be written in a portable fashion, so that the custom
958inspect function is used in an Node.js environment and ignored in the browser.
959The `util.inspect()` function itself is passed as third argument to the custom
960inspect function to allow further portability.
961
962```js
963const customInspectSymbol = Symbol.for('nodejs.util.inspect.custom');
964
965class Password {
966  constructor(value) {
967    this.value = value;
968  }
969
970  toString() {
971    return 'xxxxxxxx';
972  }
973
974  [customInspectSymbol](depth, inspectOptions, inspect) {
975    return `Password <${this.toString()}>`;
976  }
977}
978
979const password = new Password('r0sebud');
980console.log(password);
981// Prints Password <xxxxxxxx>
982```
983
984See [Custom inspection functions on Objects][] for more details.
985
986### `util.inspect.defaultOptions`
987
988<!-- YAML
989added: v6.4.0
990-->
991
992The `defaultOptions` value allows customization of the default options used by
993`util.inspect`. This is useful for functions like `console.log` or
994`util.format` which implicitly call into `util.inspect`. It shall be set to an
995object containing one or more valid [`util.inspect()`][] options. Setting
996option properties directly is also supported.
997
998```js
999const util = require('node:util');
1000const arr = Array(101).fill(0);
1001
1002console.log(arr); // Logs the truncated array
1003util.inspect.defaultOptions.maxArrayLength = null;
1004console.log(arr); // logs the full array
1005```
1006
1007## `util.isDeepStrictEqual(val1, val2)`
1008
1009<!-- YAML
1010added: v9.0.0
1011-->
1012
1013* `val1` {any}
1014* `val2` {any}
1015* Returns: {boolean}
1016
1017Returns `true` if there is deep strict equality between `val1` and `val2`.
1018Otherwise, returns `false`.
1019
1020See [`assert.deepStrictEqual()`][] for more information about deep strict
1021equality.
1022
1023## Class: `util.MIMEType`
1024
1025<!-- YAML
1026added: v18.13.0
1027-->
1028
1029> Stability: 1 - Experimental
1030
1031An implementation of [the MIMEType class](https://bmeck.github.io/node-proposal-mime-api/).
1032
1033In accordance with browser conventions, all properties of `MIMEType` objects
1034are implemented as getters and setters on the class prototype, rather than as
1035data properties on the object itself.
1036
1037A MIME string is a structured string containing multiple meaningful
1038components. When parsed, a `MIMEType` object is returned containing
1039properties for each of these components.
1040
1041### Constructor: `new MIMEType(input)`
1042
1043* `input` {string} The input MIME to parse
1044
1045Creates a new `MIMEType` object by parsing the `input`.
1046
1047```mjs
1048import { MIMEType } from 'node:util';
1049
1050const myMIME = new MIMEType('text/plain');
1051```
1052
1053```cjs
1054const { MIMEType } = require('node:util');
1055
1056const myMIME = new MIMEType('text/plain');
1057```
1058
1059A `TypeError` will be thrown if the `input` is not a valid MIME. Note
1060that an effort will be made to coerce the given values into strings. For
1061instance:
1062
1063```mjs
1064import { MIMEType } from 'node:util';
1065const myMIME = new MIMEType({ toString: () => 'text/plain' });
1066console.log(String(myMIME));
1067// Prints: text/plain
1068```
1069
1070```cjs
1071const { MIMEType } = require('node:util');
1072const myMIME = new MIMEType({ toString: () => 'text/plain' });
1073console.log(String(myMIME));
1074// Prints: text/plain
1075```
1076
1077### `mime.type`
1078
1079* {string}
1080
1081Gets and sets the type portion of the MIME.
1082
1083```mjs
1084import { MIMEType } from 'node:util';
1085
1086const myMIME = new MIMEType('text/javascript');
1087console.log(myMIME.type);
1088// Prints: text
1089myMIME.type = 'application';
1090console.log(myMIME.type);
1091// Prints: application
1092console.log(String(myMIME));
1093// Prints: application/javascript
1094```
1095
1096```cjs
1097const { MIMEType } = require('node:util');
1098
1099const myMIME = new MIMEType('text/javascript');
1100console.log(myMIME.type);
1101// Prints: text
1102myMIME.type = 'application';
1103console.log(myMIME.type);
1104// Prints: application
1105console.log(String(myMIME));
1106// Prints: application/javascript
1107```
1108
1109### `mime.subtype`
1110
1111* {string}
1112
1113Gets and sets the subtype portion of the MIME.
1114
1115```mjs
1116import { MIMEType } from 'node:util';
1117
1118const myMIME = new MIMEType('text/ecmascript');
1119console.log(myMIME.subtype);
1120// Prints: ecmascript
1121myMIME.subtype = 'javascript';
1122console.log(myMIME.subtype);
1123// Prints: javascript
1124console.log(String(myMIME));
1125// Prints: text/javascript
1126```
1127
1128```cjs
1129const { MIMEType } = require('node:util');
1130
1131const myMIME = new MIMEType('text/ecmascript');
1132console.log(myMIME.subtype);
1133// Prints: ecmascript
1134myMIME.subtype = 'javascript';
1135console.log(myMIME.subtype);
1136// Prints: javascript
1137console.log(String(myMIME));
1138// Prints: text/javascript
1139```
1140
1141### `mime.essence`
1142
1143* {string}
1144
1145Gets the essence of the MIME. This property is read only.
1146Use `mime.type` or `mime.subtype` to alter the MIME.
1147
1148```mjs
1149import { MIMEType } from 'node:util';
1150
1151const myMIME = new MIMEType('text/javascript;key=value');
1152console.log(myMIME.essence);
1153// Prints: text/javascript
1154myMIME.type = 'application';
1155console.log(myMIME.essence);
1156// Prints: application/javascript
1157console.log(String(myMIME));
1158// Prints: application/javascript;key=value
1159```
1160
1161```cjs
1162const { MIMEType } = require('node:util');
1163
1164const myMIME = new MIMEType('text/javascript;key=value');
1165console.log(myMIME.essence);
1166// Prints: text/javascript
1167myMIME.type = 'application';
1168console.log(myMIME.essence);
1169// Prints: application/javascript
1170console.log(String(myMIME));
1171// Prints: application/javascript;key=value
1172```
1173
1174### `mime.params`
1175
1176* {MIMEParams}
1177
1178Gets the [`MIMEParams`][] object representing the
1179parameters of the MIME. This property is read-only. See
1180[`MIMEParams`][] documentation for details.
1181
1182### `mime.toString()`
1183
1184* Returns: {string}
1185
1186The `toString()` method on the `MIMEType` object returns the serialized MIME.
1187
1188Because of the need for standard compliance, this method does not allow users
1189to customize the serialization process of the MIME.
1190
1191### `mime.toJSON()`
1192
1193* Returns: {string}
1194
1195Alias for [`mime.toString()`][].
1196
1197This method is automatically called when an `MIMEType` object is serialized
1198with [`JSON.stringify()`][].
1199
1200```mjs
1201import { MIMEType } from 'node:util';
1202
1203const myMIMES = [
1204  new MIMEType('image/png'),
1205  new MIMEType('image/gif'),
1206];
1207console.log(JSON.stringify(myMIMES));
1208// Prints: ["image/png", "image/gif"]
1209```
1210
1211```cjs
1212const { MIMEType } = require('node:util');
1213
1214const myMIMES = [
1215  new MIMEType('image/png'),
1216  new MIMEType('image/gif'),
1217];
1218console.log(JSON.stringify(myMIMES));
1219// Prints: ["image/png", "image/gif"]
1220```
1221
1222## Class: `util.MIMEParams`
1223
1224<!-- YAML
1225added: v18.13.0
1226-->
1227
1228The `MIMEParams` API provides read and write access to the parameters of a
1229`MIMEType`.
1230
1231### Constructor: `new MIMEParams()`
1232
1233Creates a new `MIMEParams` object by with empty parameters
1234
1235```mjs
1236import { MIMEParams } from 'node:util';
1237
1238const myParams = new MIMEParams();
1239```
1240
1241```cjs
1242const { MIMEParams } = require('node:util');
1243
1244const myParams = new MIMEParams();
1245```
1246
1247### `mimeParams.delete(name)`
1248
1249* `name` {string}
1250
1251Remove all name-value pairs whose name is `name`.
1252
1253### `mimeParams.entries()`
1254
1255* Returns: {Iterator}
1256
1257Returns an iterator over each of the name-value pairs in the parameters.
1258Each item of the iterator is a JavaScript `Array`. The first item of the array
1259is the `name`, the second item of the array is the `value`.
1260
1261### `mimeParams.get(name)`
1262
1263* `name` {string}
1264* Returns: {string} or `null` if there is no name-value pair with the given
1265  `name`.
1266
1267Returns the value of the first name-value pair whose name is `name`. If there
1268are no such pairs, `null` is returned.
1269
1270### `mimeParams.has(name)`
1271
1272* `name` {string}
1273* Returns: {boolean}
1274
1275Returns `true` if there is at least one name-value pair whose name is `name`.
1276
1277### `mimeParams.keys()`
1278
1279* Returns: {Iterator}
1280
1281Returns an iterator over the names of each name-value pair.
1282
1283```mjs
1284import { MIMEType } from 'node:util';
1285
1286const { params } = new MIMEType('text/plain;foo=0;bar=1');
1287for (const name of params.keys()) {
1288  console.log(name);
1289}
1290// Prints:
1291//   foo
1292//   bar
1293```
1294
1295```cjs
1296const { MIMEType } = require('node:util');
1297
1298const { params } = new MIMEType('text/plain;foo=0;bar=1');
1299for (const name of params.keys()) {
1300  console.log(name);
1301}
1302// Prints:
1303//   foo
1304//   bar
1305```
1306
1307### `mimeParams.set(name, value)`
1308
1309* `name` {string}
1310* `value` {string}
1311
1312Sets the value in the `MIMEParams` object associated with `name` to
1313`value`. If there are any pre-existing name-value pairs whose names are `name`,
1314set the first such pair's value to `value`.
1315
1316```mjs
1317import { MIMEType } from 'node:util';
1318
1319const { params } = new MIMEType('text/plain;foo=0;bar=1');
1320params.set('foo', 'def');
1321params.set('baz', 'xyz');
1322console.log(params.toString());
1323// Prints: foo=def&bar=1&baz=xyz
1324```
1325
1326```cjs
1327const { MIMEType } = require('node:util');
1328
1329const { params } = new MIMEType('text/plain;foo=0;bar=1');
1330params.set('foo', 'def');
1331params.set('baz', 'xyz');
1332console.log(params.toString());
1333// Prints: foo=def&bar=1&baz=xyz
1334```
1335
1336### `mimeParams.values()`
1337
1338* Returns: {Iterator}
1339
1340Returns an iterator over the values of each name-value pair.
1341
1342### `mimeParams[@@iterator]()`
1343
1344* Returns: {Iterator}
1345
1346Alias for [`mimeParams.entries()`][].
1347
1348```mjs
1349import { MIMEType } from 'node:util';
1350
1351const { params } = new MIMEType('text/plain;foo=bar;xyz=baz');
1352for (const [name, value] of params) {
1353  console.log(name, value);
1354}
1355// Prints:
1356//   foo bar
1357//   xyz baz
1358```
1359
1360```cjs
1361const { MIMEType } = require('node:util');
1362
1363const { params } = new MIMEType('text/plain;foo=bar;xyz=baz');
1364for (const [name, value] of params) {
1365  console.log(name, value);
1366}
1367// Prints:
1368//   foo bar
1369//   xyz baz
1370```
1371
1372## `util.parseArgs([config])`
1373
1374<!-- YAML
1375added: v18.3.0
1376changes:
1377  - version: v18.11.0
1378    pr-url: https://github.com/nodejs/node/pull/44631
1379    description: Add support for default values in input `config`.
1380  - version:
1381    - v18.7.0
1382    - v16.17.0
1383    pr-url: https://github.com/nodejs/node/pull/43459
1384    description: add support for returning detailed parse information
1385                 using `tokens` in input `config` and returned properties.
1386-->
1387
1388> Stability: 1 - Experimental
1389
1390* `config` {Object} Used to provide arguments for parsing and to configure
1391  the parser. `config` supports the following properties:
1392  * `args` {string\[]} array of argument strings. **Default:** `process.argv`
1393    with `execPath` and `filename` removed.
1394  * `options` {Object} Used to describe arguments known to the parser.
1395    Keys of `options` are the long names of options and values are an
1396    {Object} accepting the following properties:
1397    * `type` {string} Type of argument, which must be either `boolean` or `string`.
1398    * `multiple` {boolean} Whether this option can be provided multiple
1399      times. If `true`, all values will be collected in an array. If
1400      `false`, values for the option are last-wins. **Default:** `false`.
1401    * `short` {string} A single character alias for the option.
1402    * `default` {string | boolean | string\[] | boolean\[]} The default option
1403      value when it is not set by args. It must be of the same type as the
1404      `type` property. When `multiple` is `true`, it must be an array.
1405  * `strict` {boolean} Should an error be thrown when unknown arguments
1406    are encountered, or when arguments are passed that do not match the
1407    `type` configured in `options`.
1408    **Default:** `true`.
1409  * `allowPositionals` {boolean} Whether this command accepts positional
1410    arguments.
1411    **Default:** `false` if `strict` is `true`, otherwise `true`.
1412  * `tokens` {boolean} Return the parsed tokens. This is useful for extending
1413    the built-in behavior, from adding additional checks through to reprocessing
1414    the tokens in different ways.
1415    **Default:** `false`.
1416
1417* Returns: {Object} The parsed command line arguments:
1418  * `values` {Object} A mapping of parsed option names with their {string}
1419    or {boolean} values.
1420  * `positionals` {string\[]} Positional arguments.
1421  * `tokens` {Object\[] | undefined} See [parseArgs tokens](#parseargs-tokens)
1422    section. Only returned if `config` includes `tokens: true`.
1423
1424Provides a higher level API for command-line argument parsing than interacting
1425with `process.argv` directly. Takes a specification for the expected arguments
1426and returns a structured object with the parsed options and positionals.
1427
1428```mjs
1429import { parseArgs } from 'node:util';
1430const args = ['-f', '--bar', 'b'];
1431const options = {
1432  foo: {
1433    type: 'boolean',
1434    short: 'f',
1435  },
1436  bar: {
1437    type: 'string',
1438  },
1439};
1440const {
1441  values,
1442  positionals,
1443} = parseArgs({ args, options });
1444console.log(values, positionals);
1445// Prints: [Object: null prototype] { foo: true, bar: 'b' } []
1446```
1447
1448```cjs
1449const { parseArgs } = require('node:util');
1450const args = ['-f', '--bar', 'b'];
1451const options = {
1452  foo: {
1453    type: 'boolean',
1454    short: 'f',
1455  },
1456  bar: {
1457    type: 'string',
1458  },
1459};
1460const {
1461  values,
1462  positionals,
1463} = parseArgs({ args, options });
1464console.log(values, positionals);
1465// Prints: [Object: null prototype] { foo: true, bar: 'b' } []
1466```
1467
1468`util.parseArgs` is experimental and behavior may change. Join the
1469conversation in [pkgjs/parseargs][] to contribute to the design.
1470
1471### `parseArgs` `tokens`
1472
1473Detailed parse information is available for adding custom behaviors by
1474specifying `tokens: true` in the configuration.
1475The returned tokens have properties describing:
1476
1477* all tokens
1478  * `kind` {string} One of 'option', 'positional', or 'option-terminator'.
1479  * `index` {number} Index of element in `args` containing token. So the
1480    source argument for a token is `args[token.index]`.
1481* option tokens
1482  * `name` {string} Long name of option.
1483  * `rawName` {string} How option used in args, like `-f` of `--foo`.
1484  * `value` {string | undefined} Option value specified in args.
1485    Undefined for boolean options.
1486  * `inlineValue` {boolean | undefined} Whether option value specified inline,
1487    like `--foo=bar`.
1488* positional tokens
1489  * `value` {string} The value of the positional argument in args (i.e. `args[index]`).
1490* option-terminator token
1491
1492The returned tokens are in the order encountered in the input args. Options
1493that appear more than once in args produce a token for each use. Short option
1494groups like `-xy` expand to a token for each option. So `-xxx` produces
1495three tokens.
1496
1497For example to use the returned tokens to add support for a negated option
1498like `--no-color`, the tokens can be reprocessed to change the value stored
1499for the negated option.
1500
1501```mjs
1502import { parseArgs } from 'node:util';
1503
1504const options = {
1505  'color': { type: 'boolean' },
1506  'no-color': { type: 'boolean' },
1507  'logfile': { type: 'string' },
1508  'no-logfile': { type: 'boolean' },
1509};
1510const { values, tokens } = parseArgs({ options, tokens: true });
1511
1512// Reprocess the option tokens and overwrite the returned values.
1513tokens
1514  .filter((token) => token.kind === 'option')
1515  .forEach((token) => {
1516    if (token.name.startsWith('no-')) {
1517      // Store foo:false for --no-foo
1518      const positiveName = token.name.slice(3);
1519      values[positiveName] = false;
1520      delete values[token.name];
1521    } else {
1522      // Resave value so last one wins if both --foo and --no-foo.
1523      values[token.name] = token.value ?? true;
1524    }
1525  });
1526
1527const color = values.color;
1528const logfile = values.logfile ?? 'default.log';
1529
1530console.log({ logfile, color });
1531```
1532
1533```cjs
1534const { parseArgs } = require('node:util');
1535
1536const options = {
1537  'color': { type: 'boolean' },
1538  'no-color': { type: 'boolean' },
1539  'logfile': { type: 'string' },
1540  'no-logfile': { type: 'boolean' },
1541};
1542const { values, tokens } = parseArgs({ options, tokens: true });
1543
1544// Reprocess the option tokens and overwrite the returned values.
1545tokens
1546  .filter((token) => token.kind === 'option')
1547  .forEach((token) => {
1548    if (token.name.startsWith('no-')) {
1549      // Store foo:false for --no-foo
1550      const positiveName = token.name.slice(3);
1551      values[positiveName] = false;
1552      delete values[token.name];
1553    } else {
1554      // Resave value so last one wins if both --foo and --no-foo.
1555      values[token.name] = token.value ?? true;
1556    }
1557  });
1558
1559const color = values.color;
1560const logfile = values.logfile ?? 'default.log';
1561
1562console.log({ logfile, color });
1563```
1564
1565Example usage showing negated options, and when an option is used
1566multiple ways then last one wins.
1567
1568```console
1569$ node negate.js
1570{ logfile: 'default.log', color: undefined }
1571$ node negate.js --no-logfile --no-color
1572{ logfile: false, color: false }
1573$ node negate.js --logfile=test.log --color
1574{ logfile: 'test.log', color: true }
1575$ node negate.js --no-logfile --logfile=test.log --color --no-color
1576{ logfile: 'test.log', color: false }
1577```
1578
1579## `util.promisify(original)`
1580
1581<!-- YAML
1582added: v8.0.0
1583-->
1584
1585* `original` {Function}
1586* Returns: {Function}
1587
1588Takes a function following the common error-first callback style, i.e. taking
1589an `(err, value) => ...` callback as the last argument, and returns a version
1590that returns promises.
1591
1592```js
1593const util = require('node:util');
1594const fs = require('node:fs');
1595
1596const stat = util.promisify(fs.stat);
1597stat('.').then((stats) => {
1598  // Do something with `stats`
1599}).catch((error) => {
1600  // Handle the error.
1601});
1602```
1603
1604Or, equivalently using `async function`s:
1605
1606```js
1607const util = require('node:util');
1608const fs = require('node:fs');
1609
1610const stat = util.promisify(fs.stat);
1611
1612async function callStat() {
1613  const stats = await stat('.');
1614  console.log(`This directory is owned by ${stats.uid}`);
1615}
1616```
1617
1618If there is an `original[util.promisify.custom]` property present, `promisify`
1619will return its value, see [Custom promisified functions][].
1620
1621`promisify()` assumes that `original` is a function taking a callback as its
1622final argument in all cases. If `original` is not a function, `promisify()`
1623will throw an error. If `original` is a function but its last argument is not
1624an error-first callback, it will still be passed an error-first
1625callback as its last argument.
1626
1627Using `promisify()` on class methods or other methods that use `this` may not
1628work as expected unless handled specially:
1629
1630```js
1631const util = require('node:util');
1632
1633class Foo {
1634  constructor() {
1635    this.a = 42;
1636  }
1637
1638  bar(callback) {
1639    callback(null, this.a);
1640  }
1641}
1642
1643const foo = new Foo();
1644
1645const naiveBar = util.promisify(foo.bar);
1646// TypeError: Cannot read property 'a' of undefined
1647// naiveBar().then(a => console.log(a));
1648
1649naiveBar.call(foo).then((a) => console.log(a)); // '42'
1650
1651const bindBar = naiveBar.bind(foo);
1652bindBar().then((a) => console.log(a)); // '42'
1653```
1654
1655### Custom promisified functions
1656
1657Using the `util.promisify.custom` symbol one can override the return value of
1658[`util.promisify()`][]:
1659
1660```js
1661const util = require('node:util');
1662
1663function doSomething(foo, callback) {
1664  // ...
1665}
1666
1667doSomething[util.promisify.custom] = (foo) => {
1668  return getPromiseSomehow();
1669};
1670
1671const promisified = util.promisify(doSomething);
1672console.log(promisified === doSomething[util.promisify.custom]);
1673// prints 'true'
1674```
1675
1676This can be useful for cases where the original function does not follow the
1677standard format of taking an error-first callback as the last argument.
1678
1679For example, with a function that takes in
1680`(foo, onSuccessCallback, onErrorCallback)`:
1681
1682```js
1683doSomething[util.promisify.custom] = (foo) => {
1684  return new Promise((resolve, reject) => {
1685    doSomething(foo, resolve, reject);
1686  });
1687};
1688```
1689
1690If `promisify.custom` is defined but is not a function, `promisify()` will
1691throw an error.
1692
1693### `util.promisify.custom`
1694
1695<!-- YAML
1696added: v8.0.0
1697changes:
1698  - version:
1699      - v13.12.0
1700      - v12.16.2
1701    pr-url: https://github.com/nodejs/node/pull/31672
1702    description: This is now defined as a shared symbol.
1703-->
1704
1705* {symbol} that can be used to declare custom promisified variants of functions,
1706  see [Custom promisified functions][].
1707
1708In addition to being accessible through `util.promisify.custom`, this
1709symbol is [registered globally][global symbol registry] and can be
1710accessed in any environment as `Symbol.for('nodejs.util.promisify.custom')`.
1711
1712For example, with a function that takes in
1713`(foo, onSuccessCallback, onErrorCallback)`:
1714
1715```js
1716const kCustomPromisifiedSymbol = Symbol.for('nodejs.util.promisify.custom');
1717
1718doSomething[kCustomPromisifiedSymbol] = (foo) => {
1719  return new Promise((resolve, reject) => {
1720    doSomething(foo, resolve, reject);
1721  });
1722};
1723```
1724
1725## `util.stripVTControlCharacters(str)`
1726
1727<!-- YAML
1728added: v16.11.0
1729-->
1730
1731* `str` {string}
1732* Returns: {string}
1733
1734Returns `str` with any ANSI escape codes removed.
1735
1736```js
1737console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m'));
1738// Prints "value"
1739```
1740
1741## Class: `util.TextDecoder`
1742
1743<!-- YAML
1744added: v8.3.0
1745-->
1746
1747An implementation of the [WHATWG Encoding Standard][] `TextDecoder` API.
1748
1749```js
1750const decoder = new TextDecoder();
1751const u8arr = new Uint8Array([72, 101, 108, 108, 111]);
1752console.log(decoder.decode(u8arr)); // Hello
1753```
1754
1755### WHATWG supported encodings
1756
1757Per the [WHATWG Encoding Standard][], the encodings supported by the
1758`TextDecoder` API are outlined in the tables below. For each encoding,
1759one or more aliases may be used.
1760
1761Different Node.js build configurations support different sets of encodings.
1762(see [Internationalization][])
1763
1764#### Encodings supported by default (with full ICU data)
1765
1766| Encoding           | Aliases                                                                                                                                                                                                                             |
1767| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1768| `'ibm866'`         | `'866'`, `'cp866'`, `'csibm866'`                                                                                                                                                                                                    |
1769| `'iso-8859-2'`     | `'csisolatin2'`, `'iso-ir-101'`, `'iso8859-2'`, `'iso88592'`, `'iso_8859-2'`, `'iso_8859-2:1987'`, `'l2'`, `'latin2'`                                                                                                               |
1770| `'iso-8859-3'`     | `'csisolatin3'`, `'iso-ir-109'`, `'iso8859-3'`, `'iso88593'`, `'iso_8859-3'`, `'iso_8859-3:1988'`, `'l3'`, `'latin3'`                                                                                                               |
1771| `'iso-8859-4'`     | `'csisolatin4'`, `'iso-ir-110'`, `'iso8859-4'`, `'iso88594'`, `'iso_8859-4'`, `'iso_8859-4:1988'`, `'l4'`, `'latin4'`                                                                                                               |
1772| `'iso-8859-5'`     | `'csisolatincyrillic'`, `'cyrillic'`, `'iso-ir-144'`, `'iso8859-5'`, `'iso88595'`, `'iso_8859-5'`, `'iso_8859-5:1988'`                                                                                                              |
1773| `'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'`                |
1774| `'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'`                                                          |
1775| `'iso-8859-8'`     | `'csiso88598e'`, `'csisolatinhebrew'`, `'hebrew'`, `'iso-8859-8-e'`, `'iso-ir-138'`, `'iso8859-8'`, `'iso88598'`, `'iso_8859-8'`, `'iso_8859-8:1988'`, `'visual'`                                                                   |
1776| `'iso-8859-8-i'`   | `'csiso88598i'`, `'logical'`                                                                                                                                                                                                        |
1777| `'iso-8859-10'`    | `'csisolatin6'`, `'iso-ir-157'`, `'iso8859-10'`, `'iso885910'`, `'l6'`, `'latin6'`                                                                                                                                                  |
1778| `'iso-8859-13'`    | `'iso8859-13'`, `'iso885913'`                                                                                                                                                                                                       |
1779| `'iso-8859-14'`    | `'iso8859-14'`, `'iso885914'`                                                                                                                                                                                                       |
1780| `'iso-8859-15'`    | `'csisolatin9'`, `'iso8859-15'`, `'iso885915'`, `'iso_8859-15'`, `'l9'`                                                                                                                                                             |
1781| `'koi8-r'`         | `'cskoi8r'`, `'koi'`, `'koi8'`, `'koi8_r'`                                                                                                                                                                                          |
1782| `'koi8-u'`         | `'koi8-ru'`                                                                                                                                                                                                                         |
1783| `'macintosh'`      | `'csmacintosh'`, `'mac'`, `'x-mac-roman'`                                                                                                                                                                                           |
1784| `'windows-874'`    | `'dos-874'`, `'iso-8859-11'`, `'iso8859-11'`, `'iso885911'`, `'tis-620'`                                                                                                                                                            |
1785| `'windows-1250'`   | `'cp1250'`, `'x-cp1250'`                                                                                                                                                                                                            |
1786| `'windows-1251'`   | `'cp1251'`, `'x-cp1251'`                                                                                                                                                                                                            |
1787| `'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'` |
1788| `'windows-1253'`   | `'cp1253'`, `'x-cp1253'`                                                                                                                                                                                                            |
1789| `'windows-1254'`   | `'cp1254'`, `'csisolatin5'`, `'iso-8859-9'`, `'iso-ir-148'`, `'iso8859-9'`, `'iso88599'`, `'iso_8859-9'`, `'iso_8859-9:1989'`, `'l5'`, `'latin5'`, `'x-cp1254'`                                                                     |
1790| `'windows-1255'`   | `'cp1255'`, `'x-cp1255'`                                                                                                                                                                                                            |
1791| `'windows-1256'`   | `'cp1256'`, `'x-cp1256'`                                                                                                                                                                                                            |
1792| `'windows-1257'`   | `'cp1257'`, `'x-cp1257'`                                                                                                                                                                                                            |
1793| `'windows-1258'`   | `'cp1258'`, `'x-cp1258'`                                                                                                                                                                                                            |
1794| `'x-mac-cyrillic'` | `'x-mac-ukrainian'`                                                                                                                                                                                                                 |
1795| `'gbk'`            | `'chinese'`, `'csgb2312'`, `'csiso58gb231280'`, `'gb2312'`, `'gb_2312'`, `'gb_2312-80'`, `'iso-ir-58'`, `'x-gbk'`                                                                                                                   |
1796| `'gb18030'`        |                                                                                                                                                                                                                                     |
1797| `'big5'`           | `'big5-hkscs'`, `'cn-big5'`, `'csbig5'`, `'x-x-big5'`                                                                                                                                                                               |
1798| `'euc-jp'`         | `'cseucpkdfmtjapanese'`, `'x-euc-jp'`                                                                                                                                                                                               |
1799| `'iso-2022-jp'`    | `'csiso2022jp'`                                                                                                                                                                                                                     |
1800| `'shift_jis'`      | `'csshiftjis'`, `'ms932'`, `'ms_kanji'`, `'shift-jis'`, `'sjis'`, `'windows-31j'`, `'x-sjis'`                                                                                                                                       |
1801| `'euc-kr'`         | `'cseuckr'`, `'csksc56011987'`, `'iso-ir-149'`, `'korean'`, `'ks_c_5601-1987'`, `'ks_c_5601-1989'`, `'ksc5601'`, `'ksc_5601'`, `'windows-949'`                                                                                      |
1802
1803#### Encodings supported when Node.js is built with the `small-icu` option
1804
1805| Encoding     | Aliases                         |
1806| ------------ | ------------------------------- |
1807| `'utf-8'`    | `'unicode-1-1-utf-8'`, `'utf8'` |
1808| `'utf-16le'` | `'utf-16'`                      |
1809| `'utf-16be'` |                                 |
1810
1811#### Encodings supported when ICU is disabled
1812
1813| Encoding     | Aliases                         |
1814| ------------ | ------------------------------- |
1815| `'utf-8'`    | `'unicode-1-1-utf-8'`, `'utf8'` |
1816| `'utf-16le'` | `'utf-16'`                      |
1817
1818The `'iso-8859-16'` encoding listed in the [WHATWG Encoding Standard][]
1819is not supported.
1820
1821### `new TextDecoder([encoding[, options]])`
1822
1823<!-- YAML
1824added: v8.3.0
1825changes:
1826  - version: v11.0.0
1827    pr-url: https://github.com/nodejs/node/pull/22281
1828    description: The class is now available on the global object.
1829-->
1830
1831* `encoding` {string} Identifies the `encoding` that this `TextDecoder` instance
1832  supports. **Default:** `'utf-8'`.
1833* `options` {Object}
1834  * `fatal` {boolean} `true` if decoding failures are fatal.
1835    This option is not supported when ICU is disabled
1836    (see [Internationalization][]). **Default:** `false`.
1837  * `ignoreBOM` {boolean} When `true`, the `TextDecoder` will include the byte
1838    order mark in the decoded result. When `false`, the byte order mark will
1839    be removed from the output. This option is only used when `encoding` is
1840    `'utf-8'`, `'utf-16be'`, or `'utf-16le'`. **Default:** `false`.
1841
1842Creates a new `TextDecoder` instance. The `encoding` may specify one of the
1843supported encodings or an alias.
1844
1845The `TextDecoder` class is also available on the global object.
1846
1847### `textDecoder.decode([input[, options]])`
1848
1849* `input` {ArrayBuffer|DataView|TypedArray} An `ArrayBuffer`, `DataView`, or
1850  `TypedArray` instance containing the encoded data.
1851* `options` {Object}
1852  * `stream` {boolean} `true` if additional chunks of data are expected.
1853    **Default:** `false`.
1854* Returns: {string}
1855
1856Decodes the `input` and returns a string. If `options.stream` is `true`, any
1857incomplete byte sequences occurring at the end of the `input` are buffered
1858internally and emitted after the next call to `textDecoder.decode()`.
1859
1860If `textDecoder.fatal` is `true`, decoding errors that occur will result in a
1861`TypeError` being thrown.
1862
1863### `textDecoder.encoding`
1864
1865* {string}
1866
1867The encoding supported by the `TextDecoder` instance.
1868
1869### `textDecoder.fatal`
1870
1871* {boolean}
1872
1873The value will be `true` if decoding errors result in a `TypeError` being
1874thrown.
1875
1876### `textDecoder.ignoreBOM`
1877
1878* {boolean}
1879
1880The value will be `true` if the decoding result will include the byte order
1881mark.
1882
1883## Class: `util.TextEncoder`
1884
1885<!-- YAML
1886added: v8.3.0
1887changes:
1888  - version: v11.0.0
1889    pr-url: https://github.com/nodejs/node/pull/22281
1890    description: The class is now available on the global object.
1891-->
1892
1893An implementation of the [WHATWG Encoding Standard][] `TextEncoder` API. All
1894instances of `TextEncoder` only support UTF-8 encoding.
1895
1896```js
1897const encoder = new TextEncoder();
1898const uint8array = encoder.encode('this is some data');
1899```
1900
1901The `TextEncoder` class is also available on the global object.
1902
1903### `textEncoder.encode([input])`
1904
1905* `input` {string} The text to encode. **Default:** an empty string.
1906* Returns: {Uint8Array}
1907
1908UTF-8 encodes the `input` string and returns a `Uint8Array` containing the
1909encoded bytes.
1910
1911### `textEncoder.encodeInto(src, dest)`
1912
1913* `src` {string} The text to encode.
1914* `dest` {Uint8Array} The array to hold the encode result.
1915* Returns: {Object}
1916  * `read` {number} The read Unicode code units of src.
1917  * `written` {number} The written UTF-8 bytes of dest.
1918
1919UTF-8 encodes the `src` string to the `dest` Uint8Array and returns an object
1920containing the read Unicode code units and written UTF-8 bytes.
1921
1922```js
1923const encoder = new TextEncoder();
1924const src = 'this is some data';
1925const dest = new Uint8Array(10);
1926const { read, written } = encoder.encodeInto(src, dest);
1927```
1928
1929### `textEncoder.encoding`
1930
1931* {string}
1932
1933The encoding supported by the `TextEncoder` instance. Always set to `'utf-8'`.
1934
1935## `util.toUSVString(string)`
1936
1937<!-- YAML
1938added:
1939  - v16.8.0
1940  - v14.18.0
1941-->
1942
1943* `string` {string}
1944
1945Returns the `string` after replacing any surrogate code points
1946(or equivalently, any unpaired surrogate code units) with the
1947Unicode "replacement character" U+FFFD.
1948
1949## `util.transferableAbortController()`
1950
1951<!-- YAML
1952added: v18.11.0
1953-->
1954
1955> Stability: 1 - Experimental
1956
1957Creates and returns an {AbortController} instance whose {AbortSignal} is marked
1958as transferable and can be used with `structuredClone()` or `postMessage()`.
1959
1960## `util.transferableAbortSignal(signal)`
1961
1962<!-- YAML
1963added: v18.11.0
1964-->
1965
1966> Stability: 1 - Experimental
1967
1968* `signal` {AbortSignal}
1969* Returns: {AbortSignal}
1970
1971Marks the given {AbortSignal} as transferable so that it can be used with
1972`structuredClone()` and `postMessage()`.
1973
1974```js
1975const signal = transferableAbortSignal(AbortSignal.timeout(100));
1976const channel = new MessageChannel();
1977channel.port2.postMessage(signal, [signal]);
1978```
1979
1980## `util.aborted(signal, resource)`
1981
1982<!-- YAML
1983added: v18.16.0
1984-->
1985
1986> Stability: 1 - Experimental
1987
1988* `signal` {AbortSignal}
1989* `resource` {Object} Any non-null entity, reference to which is held weakly.
1990* Returns: {Promise}
1991
1992Listens to abort event on the provided `signal` and
1993returns a promise that is fulfilled when the `signal` is
1994aborted. If the passed `resource` is garbage collected before the `signal` is
1995aborted, the returned promise shall remain pending indefinitely.
1996
1997```cjs
1998const { aborted } = require('node:util');
1999
2000const dependent = obtainSomethingAbortable();
2001
2002aborted(dependent.signal, dependent).then(() => {
2003  // Do something when dependent is aborted.
2004});
2005
2006dependent.on('event', () => {
2007  dependent.abort();
2008});
2009```
2010
2011```mjs
2012import { aborted } from 'node:util';
2013
2014const dependent = obtainSomethingAbortable();
2015
2016aborted(dependent.signal, dependent).then(() => {
2017  // Do something when dependent is aborted.
2018});
2019
2020dependent.on('event', () => {
2021  dependent.abort();
2022});
2023```
2024
2025## `util.types`
2026
2027<!-- YAML
2028added: v10.0.0
2029changes:
2030  - version: v15.3.0
2031    pr-url: https://github.com/nodejs/node/pull/34055
2032    description: Exposed as `require('util/types')`.
2033-->
2034
2035`util.types` provides type checks for different kinds of built-in objects.
2036Unlike `instanceof` or `Object.prototype.toString.call(value)`, these checks do
2037not inspect properties of the object that are accessible from JavaScript (like
2038their prototype), and usually have the overhead of calling into C++.
2039
2040The result generally does not make any guarantees about what kinds of
2041properties or behavior a value exposes in JavaScript. They are primarily
2042useful for addon developers who prefer to do type checking in JavaScript.
2043
2044The API is accessible via `require('node:util').types` or `require('node:util/types')`.
2045
2046### `util.types.isAnyArrayBuffer(value)`
2047
2048<!-- YAML
2049added: v10.0.0
2050-->
2051
2052* `value` {any}
2053* Returns: {boolean}
2054
2055Returns `true` if the value is a built-in [`ArrayBuffer`][] or
2056[`SharedArrayBuffer`][] instance.
2057
2058See also [`util.types.isArrayBuffer()`][] and
2059[`util.types.isSharedArrayBuffer()`][].
2060
2061```js
2062util.types.isAnyArrayBuffer(new ArrayBuffer());  // Returns true
2063util.types.isAnyArrayBuffer(new SharedArrayBuffer());  // Returns true
2064```
2065
2066### `util.types.isArrayBufferView(value)`
2067
2068<!-- YAML
2069added: v10.0.0
2070-->
2071
2072* `value` {any}
2073* Returns: {boolean}
2074
2075Returns `true` if the value is an instance of one of the [`ArrayBuffer`][]
2076views, such as typed array objects or [`DataView`][]. Equivalent to
2077[`ArrayBuffer.isView()`][].
2078
2079```js
2080util.types.isArrayBufferView(new Int8Array());  // true
2081util.types.isArrayBufferView(Buffer.from('hello world')); // true
2082util.types.isArrayBufferView(new DataView(new ArrayBuffer(16)));  // true
2083util.types.isArrayBufferView(new ArrayBuffer());  // false
2084```
2085
2086### `util.types.isArgumentsObject(value)`
2087
2088<!-- YAML
2089added: v10.0.0
2090-->
2091
2092* `value` {any}
2093* Returns: {boolean}
2094
2095Returns `true` if the value is an `arguments` object.
2096
2097<!-- eslint-disable prefer-rest-params -->
2098
2099```js
2100function foo() {
2101  util.types.isArgumentsObject(arguments);  // Returns true
2102}
2103```
2104
2105### `util.types.isArrayBuffer(value)`
2106
2107<!-- YAML
2108added: v10.0.0
2109-->
2110
2111* `value` {any}
2112* Returns: {boolean}
2113
2114Returns `true` if the value is a built-in [`ArrayBuffer`][] instance.
2115This does _not_ include [`SharedArrayBuffer`][] instances. Usually, it is
2116desirable to test for both; See [`util.types.isAnyArrayBuffer()`][] for that.
2117
2118```js
2119util.types.isArrayBuffer(new ArrayBuffer());  // Returns true
2120util.types.isArrayBuffer(new SharedArrayBuffer());  // Returns false
2121```
2122
2123### `util.types.isAsyncFunction(value)`
2124
2125<!-- YAML
2126added: v10.0.0
2127-->
2128
2129* `value` {any}
2130* Returns: {boolean}
2131
2132Returns `true` if the value is an [async function][].
2133This only reports back what the JavaScript engine is seeing;
2134in particular, the return value may not match the original source code if
2135a transpilation tool was used.
2136
2137```js
2138util.types.isAsyncFunction(function foo() {});  // Returns false
2139util.types.isAsyncFunction(async function foo() {});  // Returns true
2140```
2141
2142### `util.types.isBigInt64Array(value)`
2143
2144<!-- YAML
2145added: v10.0.0
2146-->
2147
2148* `value` {any}
2149* Returns: {boolean}
2150
2151Returns `true` if the value is a `BigInt64Array` instance.
2152
2153```js
2154util.types.isBigInt64Array(new BigInt64Array());   // Returns true
2155util.types.isBigInt64Array(new BigUint64Array());  // Returns false
2156```
2157
2158### `util.types.isBigUint64Array(value)`
2159
2160<!-- YAML
2161added: v10.0.0
2162-->
2163
2164* `value` {any}
2165* Returns: {boolean}
2166
2167Returns `true` if the value is a `BigUint64Array` instance.
2168
2169```js
2170util.types.isBigUint64Array(new BigInt64Array());   // Returns false
2171util.types.isBigUint64Array(new BigUint64Array());  // Returns true
2172```
2173
2174### `util.types.isBooleanObject(value)`
2175
2176<!-- YAML
2177added: v10.0.0
2178-->
2179
2180* `value` {any}
2181* Returns: {boolean}
2182
2183Returns `true` if the value is a boolean object, e.g. created
2184by `new Boolean()`.
2185
2186```js
2187util.types.isBooleanObject(false);  // Returns false
2188util.types.isBooleanObject(true);   // Returns false
2189util.types.isBooleanObject(new Boolean(false)); // Returns true
2190util.types.isBooleanObject(new Boolean(true));  // Returns true
2191util.types.isBooleanObject(Boolean(false)); // Returns false
2192util.types.isBooleanObject(Boolean(true));  // Returns false
2193```
2194
2195### `util.types.isBoxedPrimitive(value)`
2196
2197<!-- YAML
2198added: v10.11.0
2199-->
2200
2201* `value` {any}
2202* Returns: {boolean}
2203
2204Returns `true` if the value is any boxed primitive object, e.g. created
2205by `new Boolean()`, `new String()` or `Object(Symbol())`.
2206
2207For example:
2208
2209```js
2210util.types.isBoxedPrimitive(false); // Returns false
2211util.types.isBoxedPrimitive(new Boolean(false)); // Returns true
2212util.types.isBoxedPrimitive(Symbol('foo')); // Returns false
2213util.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true
2214util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true
2215```
2216
2217### `util.types.isCryptoKey(value)`
2218
2219<!-- YAML
2220added: v16.2.0
2221-->
2222
2223* `value` {Object}
2224* Returns: {boolean}
2225
2226Returns `true` if `value` is a {CryptoKey}, `false` otherwise.
2227
2228### `util.types.isDataView(value)`
2229
2230<!-- YAML
2231added: v10.0.0
2232-->
2233
2234* `value` {any}
2235* Returns: {boolean}
2236
2237Returns `true` if the value is a built-in [`DataView`][] instance.
2238
2239```js
2240const ab = new ArrayBuffer(20);
2241util.types.isDataView(new DataView(ab));  // Returns true
2242util.types.isDataView(new Float64Array());  // Returns false
2243```
2244
2245See also [`ArrayBuffer.isView()`][].
2246
2247### `util.types.isDate(value)`
2248
2249<!-- YAML
2250added: v10.0.0
2251-->
2252
2253* `value` {any}
2254* Returns: {boolean}
2255
2256Returns `true` if the value is a built-in [`Date`][] instance.
2257
2258```js
2259util.types.isDate(new Date());  // Returns true
2260```
2261
2262### `util.types.isExternal(value)`
2263
2264<!-- YAML
2265added: v10.0.0
2266-->
2267
2268* `value` {any}
2269* Returns: {boolean}
2270
2271Returns `true` if the value is a native `External` value.
2272
2273A native `External` value is a special type of object that contains a
2274raw C++ pointer (`void*`) for access from native code, and has no other
2275properties. Such objects are created either by Node.js internals or native
2276addons. In JavaScript, they are [frozen][`Object.freeze()`] objects with a
2277`null` prototype.
2278
2279```c
2280#include <js_native_api.h>
2281#include <stdlib.h>
2282napi_value result;
2283static napi_value MyNapi(napi_env env, napi_callback_info info) {
2284  int* raw = (int*) malloc(1024);
2285  napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result);
2286  if (status != napi_ok) {
2287    napi_throw_error(env, NULL, "napi_create_external failed");
2288    return NULL;
2289  }
2290  return result;
2291}
2292...
2293DECLARE_NAPI_PROPERTY("myNapi", MyNapi)
2294...
2295```
2296
2297```js
2298const native = require('napi_addon.node');
2299const data = native.myNapi();
2300util.types.isExternal(data); // returns true
2301util.types.isExternal(0); // returns false
2302util.types.isExternal(new String('foo')); // returns false
2303```
2304
2305For further information on `napi_create_external`, refer to
2306[`napi_create_external()`][].
2307
2308### `util.types.isFloat32Array(value)`
2309
2310<!-- YAML
2311added: v10.0.0
2312-->
2313
2314* `value` {any}
2315* Returns: {boolean}
2316
2317Returns `true` if the value is a built-in [`Float32Array`][] instance.
2318
2319```js
2320util.types.isFloat32Array(new ArrayBuffer());  // Returns false
2321util.types.isFloat32Array(new Float32Array());  // Returns true
2322util.types.isFloat32Array(new Float64Array());  // Returns false
2323```
2324
2325### `util.types.isFloat64Array(value)`
2326
2327<!-- YAML
2328added: v10.0.0
2329-->
2330
2331* `value` {any}
2332* Returns: {boolean}
2333
2334Returns `true` if the value is a built-in [`Float64Array`][] instance.
2335
2336```js
2337util.types.isFloat64Array(new ArrayBuffer());  // Returns false
2338util.types.isFloat64Array(new Uint8Array());  // Returns false
2339util.types.isFloat64Array(new Float64Array());  // Returns true
2340```
2341
2342### `util.types.isGeneratorFunction(value)`
2343
2344<!-- YAML
2345added: v10.0.0
2346-->
2347
2348* `value` {any}
2349* Returns: {boolean}
2350
2351Returns `true` if the value is a generator function.
2352This only reports back what the JavaScript engine is seeing;
2353in particular, the return value may not match the original source code if
2354a transpilation tool was used.
2355
2356```js
2357util.types.isGeneratorFunction(function foo() {});  // Returns false
2358util.types.isGeneratorFunction(function* foo() {});  // Returns true
2359```
2360
2361### `util.types.isGeneratorObject(value)`
2362
2363<!-- YAML
2364added: v10.0.0
2365-->
2366
2367* `value` {any}
2368* Returns: {boolean}
2369
2370Returns `true` if the value is a generator object as returned from a
2371built-in generator function.
2372This only reports back what the JavaScript engine is seeing;
2373in particular, the return value may not match the original source code if
2374a transpilation tool was used.
2375
2376```js
2377function* foo() {}
2378const generator = foo();
2379util.types.isGeneratorObject(generator);  // Returns true
2380```
2381
2382### `util.types.isInt8Array(value)`
2383
2384<!-- YAML
2385added: v10.0.0
2386-->
2387
2388* `value` {any}
2389* Returns: {boolean}
2390
2391Returns `true` if the value is a built-in [`Int8Array`][] instance.
2392
2393```js
2394util.types.isInt8Array(new ArrayBuffer());  // Returns false
2395util.types.isInt8Array(new Int8Array());  // Returns true
2396util.types.isInt8Array(new Float64Array());  // Returns false
2397```
2398
2399### `util.types.isInt16Array(value)`
2400
2401<!-- YAML
2402added: v10.0.0
2403-->
2404
2405* `value` {any}
2406* Returns: {boolean}
2407
2408Returns `true` if the value is a built-in [`Int16Array`][] instance.
2409
2410```js
2411util.types.isInt16Array(new ArrayBuffer());  // Returns false
2412util.types.isInt16Array(new Int16Array());  // Returns true
2413util.types.isInt16Array(new Float64Array());  // Returns false
2414```
2415
2416### `util.types.isInt32Array(value)`
2417
2418<!-- YAML
2419added: v10.0.0
2420-->
2421
2422* `value` {any}
2423* Returns: {boolean}
2424
2425Returns `true` if the value is a built-in [`Int32Array`][] instance.
2426
2427```js
2428util.types.isInt32Array(new ArrayBuffer());  // Returns false
2429util.types.isInt32Array(new Int32Array());  // Returns true
2430util.types.isInt32Array(new Float64Array());  // Returns false
2431```
2432
2433### `util.types.isKeyObject(value)`
2434
2435<!-- YAML
2436added: v16.2.0
2437-->
2438
2439* `value` {Object}
2440* Returns: {boolean}
2441
2442Returns `true` if `value` is a {KeyObject}, `false` otherwise.
2443
2444### `util.types.isMap(value)`
2445
2446<!-- YAML
2447added: v10.0.0
2448-->
2449
2450* `value` {any}
2451* Returns: {boolean}
2452
2453Returns `true` if the value is a built-in [`Map`][] instance.
2454
2455```js
2456util.types.isMap(new Map());  // Returns true
2457```
2458
2459### `util.types.isMapIterator(value)`
2460
2461<!-- YAML
2462added: v10.0.0
2463-->
2464
2465* `value` {any}
2466* Returns: {boolean}
2467
2468Returns `true` if the value is an iterator returned for a built-in
2469[`Map`][] instance.
2470
2471```js
2472const map = new Map();
2473util.types.isMapIterator(map.keys());  // Returns true
2474util.types.isMapIterator(map.values());  // Returns true
2475util.types.isMapIterator(map.entries());  // Returns true
2476util.types.isMapIterator(map[Symbol.iterator]());  // Returns true
2477```
2478
2479### `util.types.isModuleNamespaceObject(value)`
2480
2481<!-- YAML
2482added: v10.0.0
2483-->
2484
2485* `value` {any}
2486* Returns: {boolean}
2487
2488Returns `true` if the value is an instance of a [Module Namespace Object][].
2489
2490<!-- eslint-skip -->
2491
2492```js
2493import * as ns from './a.js';
2494
2495util.types.isModuleNamespaceObject(ns);  // Returns true
2496```
2497
2498### `util.types.isNativeError(value)`
2499
2500<!-- YAML
2501added: v10.0.0
2502-->
2503
2504* `value` {any}
2505* Returns: {boolean}
2506
2507Returns `true` if the value was returned by the constructor of a
2508[built-in `Error` type][].
2509
2510```js
2511console.log(util.types.isNativeError(new Error()));  // true
2512console.log(util.types.isNativeError(new TypeError()));  // true
2513console.log(util.types.isNativeError(new RangeError()));  // true
2514```
2515
2516Subclasses of the native error types are also native errors:
2517
2518```js
2519class MyError extends Error {}
2520console.log(util.types.isNativeError(new MyError()));  // true
2521```
2522
2523A value being `instanceof` a native error class is not equivalent to `isNativeError()`
2524returning `true` for that value. `isNativeError()` returns `true` for errors
2525which come from a different [realm][] while `instanceof Error` returns `false`
2526for these errors:
2527
2528```js
2529const vm = require('node:vm');
2530const context = vm.createContext({});
2531const myError = vm.runInContext('new Error()', context);
2532console.log(util.types.isNativeError(myError)); // true
2533console.log(myError instanceof Error); // false
2534```
2535
2536Conversely, `isNativeError()` returns `false` for all objects which were not
2537returned by the constructor of a native error. That includes values
2538which are `instanceof` native errors:
2539
2540```js
2541const myError = { __proto__: Error.prototype };
2542console.log(util.types.isNativeError(myError)); // false
2543console.log(myError instanceof Error); // true
2544```
2545
2546### `util.types.isNumberObject(value)`
2547
2548<!-- YAML
2549added: v10.0.0
2550-->
2551
2552* `value` {any}
2553* Returns: {boolean}
2554
2555Returns `true` if the value is a number object, e.g. created
2556by `new Number()`.
2557
2558```js
2559util.types.isNumberObject(0);  // Returns false
2560util.types.isNumberObject(new Number(0));   // Returns true
2561```
2562
2563### `util.types.isPromise(value)`
2564
2565<!-- YAML
2566added: v10.0.0
2567-->
2568
2569* `value` {any}
2570* Returns: {boolean}
2571
2572Returns `true` if the value is a built-in [`Promise`][].
2573
2574```js
2575util.types.isPromise(Promise.resolve(42));  // Returns true
2576```
2577
2578### `util.types.isProxy(value)`
2579
2580<!-- YAML
2581added: v10.0.0
2582-->
2583
2584* `value` {any}
2585* Returns: {boolean}
2586
2587Returns `true` if the value is a [`Proxy`][] instance.
2588
2589```js
2590const target = {};
2591const proxy = new Proxy(target, {});
2592util.types.isProxy(target);  // Returns false
2593util.types.isProxy(proxy);  // Returns true
2594```
2595
2596### `util.types.isRegExp(value)`
2597
2598<!-- YAML
2599added: v10.0.0
2600-->
2601
2602* `value` {any}
2603* Returns: {boolean}
2604
2605Returns `true` if the value is a regular expression object.
2606
2607```js
2608util.types.isRegExp(/abc/);  // Returns true
2609util.types.isRegExp(new RegExp('abc'));  // Returns true
2610```
2611
2612### `util.types.isSet(value)`
2613
2614<!-- YAML
2615added: v10.0.0
2616-->
2617
2618* `value` {any}
2619* Returns: {boolean}
2620
2621Returns `true` if the value is a built-in [`Set`][] instance.
2622
2623```js
2624util.types.isSet(new Set());  // Returns true
2625```
2626
2627### `util.types.isSetIterator(value)`
2628
2629<!-- YAML
2630added: v10.0.0
2631-->
2632
2633* `value` {any}
2634* Returns: {boolean}
2635
2636Returns `true` if the value is an iterator returned for a built-in
2637[`Set`][] instance.
2638
2639```js
2640const set = new Set();
2641util.types.isSetIterator(set.keys());  // Returns true
2642util.types.isSetIterator(set.values());  // Returns true
2643util.types.isSetIterator(set.entries());  // Returns true
2644util.types.isSetIterator(set[Symbol.iterator]());  // Returns true
2645```
2646
2647### `util.types.isSharedArrayBuffer(value)`
2648
2649<!-- YAML
2650added: v10.0.0
2651-->
2652
2653* `value` {any}
2654* Returns: {boolean}
2655
2656Returns `true` if the value is a built-in [`SharedArrayBuffer`][] instance.
2657This does _not_ include [`ArrayBuffer`][] instances. Usually, it is
2658desirable to test for both; See [`util.types.isAnyArrayBuffer()`][] for that.
2659
2660```js
2661util.types.isSharedArrayBuffer(new ArrayBuffer());  // Returns false
2662util.types.isSharedArrayBuffer(new SharedArrayBuffer());  // Returns true
2663```
2664
2665### `util.types.isStringObject(value)`
2666
2667<!-- YAML
2668added: v10.0.0
2669-->
2670
2671* `value` {any}
2672* Returns: {boolean}
2673
2674Returns `true` if the value is a string object, e.g. created
2675by `new String()`.
2676
2677```js
2678util.types.isStringObject('foo');  // Returns false
2679util.types.isStringObject(new String('foo'));   // Returns true
2680```
2681
2682### `util.types.isSymbolObject(value)`
2683
2684<!-- YAML
2685added: v10.0.0
2686-->
2687
2688* `value` {any}
2689* Returns: {boolean}
2690
2691Returns `true` if the value is a symbol object, created
2692by calling `Object()` on a `Symbol` primitive.
2693
2694```js
2695const symbol = Symbol('foo');
2696util.types.isSymbolObject(symbol);  // Returns false
2697util.types.isSymbolObject(Object(symbol));   // Returns true
2698```
2699
2700### `util.types.isTypedArray(value)`
2701
2702<!-- YAML
2703added: v10.0.0
2704-->
2705
2706* `value` {any}
2707* Returns: {boolean}
2708
2709Returns `true` if the value is a built-in [`TypedArray`][] instance.
2710
2711```js
2712util.types.isTypedArray(new ArrayBuffer());  // Returns false
2713util.types.isTypedArray(new Uint8Array());  // Returns true
2714util.types.isTypedArray(new Float64Array());  // Returns true
2715```
2716
2717See also [`ArrayBuffer.isView()`][].
2718
2719### `util.types.isUint8Array(value)`
2720
2721<!-- YAML
2722added: v10.0.0
2723-->
2724
2725* `value` {any}
2726* Returns: {boolean}
2727
2728Returns `true` if the value is a built-in [`Uint8Array`][] instance.
2729
2730```js
2731util.types.isUint8Array(new ArrayBuffer());  // Returns false
2732util.types.isUint8Array(new Uint8Array());  // Returns true
2733util.types.isUint8Array(new Float64Array());  // Returns false
2734```
2735
2736### `util.types.isUint8ClampedArray(value)`
2737
2738<!-- YAML
2739added: v10.0.0
2740-->
2741
2742* `value` {any}
2743* Returns: {boolean}
2744
2745Returns `true` if the value is a built-in [`Uint8ClampedArray`][] instance.
2746
2747```js
2748util.types.isUint8ClampedArray(new ArrayBuffer());  // Returns false
2749util.types.isUint8ClampedArray(new Uint8ClampedArray());  // Returns true
2750util.types.isUint8ClampedArray(new Float64Array());  // Returns false
2751```
2752
2753### `util.types.isUint16Array(value)`
2754
2755<!-- YAML
2756added: v10.0.0
2757-->
2758
2759* `value` {any}
2760* Returns: {boolean}
2761
2762Returns `true` if the value is a built-in [`Uint16Array`][] instance.
2763
2764```js
2765util.types.isUint16Array(new ArrayBuffer());  // Returns false
2766util.types.isUint16Array(new Uint16Array());  // Returns true
2767util.types.isUint16Array(new Float64Array());  // Returns false
2768```
2769
2770### `util.types.isUint32Array(value)`
2771
2772<!-- YAML
2773added: v10.0.0
2774-->
2775
2776* `value` {any}
2777* Returns: {boolean}
2778
2779Returns `true` if the value is a built-in [`Uint32Array`][] instance.
2780
2781```js
2782util.types.isUint32Array(new ArrayBuffer());  // Returns false
2783util.types.isUint32Array(new Uint32Array());  // Returns true
2784util.types.isUint32Array(new Float64Array());  // Returns false
2785```
2786
2787### `util.types.isWeakMap(value)`
2788
2789<!-- YAML
2790added: v10.0.0
2791-->
2792
2793* `value` {any}
2794* Returns: {boolean}
2795
2796Returns `true` if the value is a built-in [`WeakMap`][] instance.
2797
2798```js
2799util.types.isWeakMap(new WeakMap());  // Returns true
2800```
2801
2802### `util.types.isWeakSet(value)`
2803
2804<!-- YAML
2805added: v10.0.0
2806-->
2807
2808* `value` {any}
2809* Returns: {boolean}
2810
2811Returns `true` if the value is a built-in [`WeakSet`][] instance.
2812
2813```js
2814util.types.isWeakSet(new WeakSet());  // Returns true
2815```
2816
2817### `util.types.isWebAssemblyCompiledModule(value)`
2818
2819<!-- YAML
2820added: v10.0.0
2821deprecated: v14.0.0
2822-->
2823
2824> Stability: 0 - Deprecated: Use `value instanceof WebAssembly.Module` instead.
2825
2826* `value` {any}
2827* Returns: {boolean}
2828
2829Returns `true` if the value is a built-in [`WebAssembly.Module`][] instance.
2830
2831```js
2832const module = new WebAssembly.Module(wasmBuffer);
2833util.types.isWebAssemblyCompiledModule(module);  // Returns true
2834```
2835
2836## Deprecated APIs
2837
2838The following APIs are deprecated and should no longer be used. Existing
2839applications and modules should be updated to find alternative approaches.
2840
2841### `util._extend(target, source)`
2842
2843<!-- YAML
2844added: v0.7.5
2845deprecated: v6.0.0
2846-->
2847
2848> Stability: 0 - Deprecated: Use [`Object.assign()`][] instead.
2849
2850* `target` {Object}
2851* `source` {Object}
2852
2853The `util._extend()` method was never intended to be used outside of internal
2854Node.js modules. The community found and used it anyway.
2855
2856It is deprecated and should not be used in new code. JavaScript comes with very
2857similar built-in functionality through [`Object.assign()`][].
2858
2859### `util.isArray(object)`
2860
2861<!-- YAML
2862added: v0.6.0
2863deprecated: v4.0.0
2864-->
2865
2866> Stability: 0 - Deprecated: Use [`Array.isArray()`][] instead.
2867
2868* `object` {any}
2869* Returns: {boolean}
2870
2871Alias for [`Array.isArray()`][].
2872
2873Returns `true` if the given `object` is an `Array`. Otherwise, returns `false`.
2874
2875```js
2876const util = require('node:util');
2877
2878util.isArray([]);
2879// Returns: true
2880util.isArray(new Array());
2881// Returns: true
2882util.isArray({});
2883// Returns: false
2884```
2885
2886### `util.isBoolean(object)`
2887
2888<!-- YAML
2889added: v0.11.5
2890deprecated: v4.0.0
2891-->
2892
2893> Stability: 0 - Deprecated: Use `typeof value === 'boolean'` instead.
2894
2895* `object` {any}
2896* Returns: {boolean}
2897
2898Returns `true` if the given `object` is a `Boolean`. Otherwise, returns `false`.
2899
2900```js
2901const util = require('node:util');
2902
2903util.isBoolean(1);
2904// Returns: false
2905util.isBoolean(0);
2906// Returns: false
2907util.isBoolean(false);
2908// Returns: true
2909```
2910
2911### `util.isBuffer(object)`
2912
2913<!-- YAML
2914added: v0.11.5
2915deprecated: v4.0.0
2916-->
2917
2918> Stability: 0 - Deprecated: Use [`Buffer.isBuffer()`][] instead.
2919
2920* `object` {any}
2921* Returns: {boolean}
2922
2923Returns `true` if the given `object` is a `Buffer`. Otherwise, returns `false`.
2924
2925```js
2926const util = require('node:util');
2927
2928util.isBuffer({ length: 0 });
2929// Returns: false
2930util.isBuffer([]);
2931// Returns: false
2932util.isBuffer(Buffer.from('hello world'));
2933// Returns: true
2934```
2935
2936### `util.isDate(object)`
2937
2938<!-- YAML
2939added: v0.6.0
2940deprecated: v4.0.0
2941-->
2942
2943> Stability: 0 - Deprecated: Use [`util.types.isDate()`][] instead.
2944
2945* `object` {any}
2946* Returns: {boolean}
2947
2948Returns `true` if the given `object` is a `Date`. Otherwise, returns `false`.
2949
2950```js
2951const util = require('node:util');
2952
2953util.isDate(new Date());
2954// Returns: true
2955util.isDate(Date());
2956// false (without 'new' returns a String)
2957util.isDate({});
2958// Returns: false
2959```
2960
2961### `util.isError(object)`
2962
2963<!-- YAML
2964added: v0.6.0
2965deprecated: v4.0.0
2966-->
2967
2968> Stability: 0 - Deprecated: Use [`util.types.isNativeError()`][] instead.
2969
2970* `object` {any}
2971* Returns: {boolean}
2972
2973Returns `true` if the given `object` is an [`Error`][]. Otherwise, returns
2974`false`.
2975
2976```js
2977const util = require('node:util');
2978
2979util.isError(new Error());
2980// Returns: true
2981util.isError(new TypeError());
2982// Returns: true
2983util.isError({ name: 'Error', message: 'an error occurred' });
2984// Returns: false
2985```
2986
2987This method relies on `Object.prototype.toString()` behavior. It is
2988possible to obtain an incorrect result when the `object` argument manipulates
2989`@@toStringTag`.
2990
2991```js
2992const util = require('node:util');
2993const obj = { name: 'Error', message: 'an error occurred' };
2994
2995util.isError(obj);
2996// Returns: false
2997obj[Symbol.toStringTag] = 'Error';
2998util.isError(obj);
2999// Returns: true
3000```
3001
3002### `util.isFunction(object)`
3003
3004<!-- YAML
3005added: v0.11.5
3006deprecated: v4.0.0
3007-->
3008
3009> Stability: 0 - Deprecated: Use `typeof value === 'function'` instead.
3010
3011* `object` {any}
3012* Returns: {boolean}
3013
3014Returns `true` if the given `object` is a `Function`. Otherwise, returns
3015`false`.
3016
3017```js
3018const util = require('node:util');
3019
3020function Foo() {}
3021const Bar = () => {};
3022
3023util.isFunction({});
3024// Returns: false
3025util.isFunction(Foo);
3026// Returns: true
3027util.isFunction(Bar);
3028// Returns: true
3029```
3030
3031### `util.isNull(object)`
3032
3033<!-- YAML
3034added: v0.11.5
3035deprecated: v4.0.0
3036-->
3037
3038> Stability: 0 - Deprecated: Use `value === null` instead.
3039
3040* `object` {any}
3041* Returns: {boolean}
3042
3043Returns `true` if the given `object` is strictly `null`. Otherwise, returns
3044`false`.
3045
3046```js
3047const util = require('node:util');
3048
3049util.isNull(0);
3050// Returns: false
3051util.isNull(undefined);
3052// Returns: false
3053util.isNull(null);
3054// Returns: true
3055```
3056
3057### `util.isNullOrUndefined(object)`
3058
3059<!-- YAML
3060added: v0.11.5
3061deprecated: v4.0.0
3062-->
3063
3064> Stability: 0 - Deprecated: Use
3065> `value === undefined || value === null` instead.
3066
3067* `object` {any}
3068* Returns: {boolean}
3069
3070Returns `true` if the given `object` is `null` or `undefined`. Otherwise,
3071returns `false`.
3072
3073```js
3074const util = require('node:util');
3075
3076util.isNullOrUndefined(0);
3077// Returns: false
3078util.isNullOrUndefined(undefined);
3079// Returns: true
3080util.isNullOrUndefined(null);
3081// Returns: true
3082```
3083
3084### `util.isNumber(object)`
3085
3086<!-- YAML
3087added: v0.11.5
3088deprecated: v4.0.0
3089-->
3090
3091> Stability: 0 - Deprecated: Use `typeof value === 'number'` instead.
3092
3093* `object` {any}
3094* Returns: {boolean}
3095
3096Returns `true` if the given `object` is a `Number`. Otherwise, returns `false`.
3097
3098```js
3099const util = require('node:util');
3100
3101util.isNumber(false);
3102// Returns: false
3103util.isNumber(Infinity);
3104// Returns: true
3105util.isNumber(0);
3106// Returns: true
3107util.isNumber(NaN);
3108// Returns: true
3109```
3110
3111### `util.isObject(object)`
3112
3113<!-- YAML
3114added: v0.11.5
3115deprecated: v4.0.0
3116-->
3117
3118> Stability: 0 - Deprecated:
3119> Use `value !== null && typeof value === 'object'` instead.
3120
3121* `object` {any}
3122* Returns: {boolean}
3123
3124Returns `true` if the given `object` is strictly an `Object` **and** not a
3125`Function` (even though functions are objects in JavaScript).
3126Otherwise, returns `false`.
3127
3128```js
3129const util = require('node:util');
3130
3131util.isObject(5);
3132// Returns: false
3133util.isObject(null);
3134// Returns: false
3135util.isObject({});
3136// Returns: true
3137util.isObject(() => {});
3138// Returns: false
3139```
3140
3141### `util.isPrimitive(object)`
3142
3143<!-- YAML
3144added: v0.11.5
3145deprecated: v4.0.0
3146-->
3147
3148> Stability: 0 - Deprecated: Use
3149> `(typeof value !== 'object' && typeof value !== 'function') || value === null`
3150> instead.
3151
3152* `object` {any}
3153* Returns: {boolean}
3154
3155Returns `true` if the given `object` is a primitive type. Otherwise, returns
3156`false`.
3157
3158```js
3159const util = require('node:util');
3160
3161util.isPrimitive(5);
3162// Returns: true
3163util.isPrimitive('foo');
3164// Returns: true
3165util.isPrimitive(false);
3166// Returns: true
3167util.isPrimitive(null);
3168// Returns: true
3169util.isPrimitive(undefined);
3170// Returns: true
3171util.isPrimitive({});
3172// Returns: false
3173util.isPrimitive(() => {});
3174// Returns: false
3175util.isPrimitive(/^$/);
3176// Returns: false
3177util.isPrimitive(new Date());
3178// Returns: false
3179```
3180
3181### `util.isRegExp(object)`
3182
3183<!-- YAML
3184added: v0.6.0
3185deprecated: v4.0.0
3186-->
3187
3188> Stability: 0 - Deprecated
3189
3190* `object` {any}
3191* Returns: {boolean}
3192
3193Returns `true` if the given `object` is a `RegExp`. Otherwise, returns `false`.
3194
3195```js
3196const util = require('node:util');
3197
3198util.isRegExp(/some regexp/);
3199// Returns: true
3200util.isRegExp(new RegExp('another regexp'));
3201// Returns: true
3202util.isRegExp({});
3203// Returns: false
3204```
3205
3206### `util.isString(object)`
3207
3208<!-- YAML
3209added: v0.11.5
3210deprecated: v4.0.0
3211-->
3212
3213> Stability: 0 - Deprecated: Use `typeof value === 'string'` instead.
3214
3215* `object` {any}
3216* Returns: {boolean}
3217
3218Returns `true` if the given `object` is a `string`. Otherwise, returns `false`.
3219
3220```js
3221const util = require('node:util');
3222
3223util.isString('');
3224// Returns: true
3225util.isString('foo');
3226// Returns: true
3227util.isString(String('foo'));
3228// Returns: true
3229util.isString(5);
3230// Returns: false
3231```
3232
3233### `util.isSymbol(object)`
3234
3235<!-- YAML
3236added: v0.11.5
3237deprecated: v4.0.0
3238-->
3239
3240> Stability: 0 - Deprecated: Use `typeof value === 'symbol'` instead.
3241
3242* `object` {any}
3243* Returns: {boolean}
3244
3245Returns `true` if the given `object` is a `Symbol`. Otherwise, returns `false`.
3246
3247```js
3248const util = require('node:util');
3249
3250util.isSymbol(5);
3251// Returns: false
3252util.isSymbol('foo');
3253// Returns: false
3254util.isSymbol(Symbol('foo'));
3255// Returns: true
3256```
3257
3258### `util.isUndefined(object)`
3259
3260<!-- YAML
3261added: v0.11.5
3262deprecated: v4.0.0
3263-->
3264
3265> Stability: 0 - Deprecated: Use `value === undefined` instead.
3266
3267* `object` {any}
3268* Returns: {boolean}
3269
3270Returns `true` if the given `object` is `undefined`. Otherwise, returns `false`.
3271
3272```js
3273const util = require('node:util');
3274
3275const foo = undefined;
3276util.isUndefined(5);
3277// Returns: false
3278util.isUndefined(foo);
3279// Returns: true
3280util.isUndefined(null);
3281// Returns: false
3282```
3283
3284### `util.log(string)`
3285
3286<!-- YAML
3287added: v0.3.0
3288deprecated: v6.0.0
3289-->
3290
3291> Stability: 0 - Deprecated: Use a third party module instead.
3292
3293* `string` {string}
3294
3295The `util.log()` method prints the given `string` to `stdout` with an included
3296timestamp.
3297
3298```js
3299const util = require('node:util');
3300
3301util.log('Timestamped message.');
3302```
3303
3304[Common System Errors]: errors.md#common-system-errors
3305[Custom inspection functions on objects]: #custom-inspection-functions-on-objects
3306[Custom promisified functions]: #custom-promisified-functions
3307[Customizing `util.inspect` colors]: #customizing-utilinspect-colors
3308[Internationalization]: intl.md
3309[Module Namespace Object]: https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects
3310[WHATWG Encoding Standard]: https://encoding.spec.whatwg.org/
3311[`'uncaughtException'`]: process.md#event-uncaughtexception
3312[`'warning'`]: process.md#event-warning
3313[`Array.isArray()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
3314[`ArrayBuffer.isView()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView
3315[`ArrayBuffer`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
3316[`Buffer.isBuffer()`]: buffer.md#static-method-bufferisbufferobj
3317[`DataView`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView
3318[`Date`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
3319[`Error`]: errors.md#class-error
3320[`Float32Array`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array
3321[`Float64Array`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array
3322[`Int16Array`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array
3323[`Int32Array`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array
3324[`Int8Array`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array
3325[`JSON.stringify()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
3326[`MIMEparams`]: #class-utilmimeparams
3327[`Map`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
3328[`Object.assign()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
3329[`Object.freeze()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze
3330[`Promise`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
3331[`Proxy`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
3332[`Set`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
3333[`SharedArrayBuffer`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer
3334[`TypedArray`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray
3335[`Uint16Array`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array
3336[`Uint32Array`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array
3337[`Uint8Array`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array
3338[`Uint8ClampedArray`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray
3339[`WeakMap`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap
3340[`WeakSet`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet
3341[`WebAssembly.Module`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module
3342[`assert.deepStrictEqual()`]: assert.md#assertdeepstrictequalactual-expected-message
3343[`console.error()`]: console.md#consoleerrordata-args
3344[`mime.toString()`]: #mimetostring
3345[`mimeParams.entries()`]: #mimeparamsentries
3346[`napi_create_external()`]: n-api.md#napi_create_external
3347[`target` and `handler`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#Terminology
3348[`tty.hasColors()`]: tty.md#writestreamhascolorscount-env
3349[`util.format()`]: #utilformatformat-args
3350[`util.inspect()`]: #utilinspectobject-options
3351[`util.promisify()`]: #utilpromisifyoriginal
3352[`util.types.isAnyArrayBuffer()`]: #utiltypesisanyarraybuffervalue
3353[`util.types.isArrayBuffer()`]: #utiltypesisarraybuffervalue
3354[`util.types.isDate()`]: #utiltypesisdatevalue
3355[`util.types.isNativeError()`]: #utiltypesisnativeerrorvalue
3356[`util.types.isSharedArrayBuffer()`]: #utiltypesissharedarraybuffervalue
3357[async function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
3358[built-in `Error` type]: https://tc39.es/ecma262/#sec-error-objects
3359[compare function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Parameters
3360[constructor]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor
3361[default sort]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
3362[global symbol registry]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/for
3363[list of deprecated APIS]: deprecations.md#list-of-deprecated-apis
3364[pkgjs/parseargs]: https://github.com/pkgjs/parseargs
3365[realm]: https://tc39.es/ecma262/#realm
3366[semantically incompatible]: https://github.com/nodejs/node/issues/4179
3367[util.inspect.custom]: #utilinspectcustom
3368