-
-
Notifications
You must be signed in to change notification settings - Fork 35.5k
Expand file tree
/
Copy pathutil.md
More file actions
2209 lines (1716 loc) Β· 60.6 KB
/
util.md
File metadata and controls
2209 lines (1716 loc) Β· 60.6 KB
Edit and raw actions
OlderNewer
Β
1
# Util
2
3
<!--introduced_in=v0.10.0-->
4
5
> Stability: 2 - Stable
6
7
The `util` module is primarily designed to support the needs of Node.js' own
8
internal APIs. However, many of the utilities are useful for application and
9
module developers as well. It can be accessed using:
10
11
```js
12
const util = require('util');
13
```
14
15
## util.callbackify(original)
16
<!-- YAML
17
added: v8.2.0
18
-->
19
20
* `original` {Function} An `async` function
21
* Returns: {Function} a callback style function
22
23
Takes an `async` function (or a function that returns a `Promise`) and returns a
24
function following the error-first callback style, i.e. taking
25
an `(err, value) => ...` callback as the last argument. In the callback, the
26
first argument will be the rejection reason (or `null` if the `Promise`
27
resolved), and the second argument will be the resolved value.
28
29
```js
30
const util = require('util');
31
32
async function fn() {
33
return 'hello world';
34
}
35
const callbackFunction = util.callbackify(fn);
36
37
callbackFunction((err, ret) => {
38
if (err) throw err;
39
console.log(ret);
40
});
41
```
42
43
Will print:
44
45
```txt
46
hello world
47
```
48
49
The callback is executed asynchronously, and will have a limited stack trace.
50
If the callback throws, the process will emit an [`'uncaughtException'`][]
51
event, and if not handled will exit.
52
53
Since `null` has a special meaning as the first argument to a callback, if a
54
wrapped function rejects a `Promise` with a falsy value as a reason, the value
55
is wrapped in an `Error` with the original value stored in a field named
56
`reason`.
57
58
```js
59
function fn() {
60
return Promise.reject(null);
61
}
62
const callbackFunction = util.callbackify(fn);
63
64
callbackFunction((err, ret) => {
65
// When the Promise was rejected with `null` it is wrapped with an Error and
66
// the original value is stored in `reason`.
67
err && err.hasOwnProperty('reason') && err.reason === null; // true
68
});
69
```
70
71
## util.debuglog(section)
72
<!-- YAML
73
added: v0.11.3
74
-->
75
76
* `section` {string} A string identifying the portion of the application for
77
which the `debuglog` function is being created.
78
* Returns: {Function} The logging function
79
80
The `util.debuglog()` method is used to create a function that conditionally
81
writes debug messages to `stderr` based on the existence of the `NODE_DEBUG`
82
environment variable. If the `section` name appears within the value of that
83
environment variable, then the returned function operates similar to
84
[`console.error()`][]. If not, then the returned function is a no-op.
85
86
```js
87
const util = require('util');
88
const debuglog = util.debuglog('foo');
89
90
debuglog('hello from foo [%d]', 123);
91
```
92
93
If this program is run with `NODE_DEBUG=foo` in the environment, then
94
it will output something like:
95
96
```txt
97
FOO 3245: hello from foo [123]
98
```
99
100
where `3245` is the process id. If it is not run with that
101
environment variable set, then it will not print anything.
102
103
The `section` supports wildcard also:
104
```js
105
const util = require('util');
106
const debuglog = util.debuglog('foo-bar');
107
108
debuglog('hi there, it\'s foo-bar [%d]', 2333);
109
```
110
111
if it is run with `NODE_DEBUG=foo*` in the environment, then it will output
112
something like:
113
```txt
114
FOO-BAR 3257: hi there, it's foo-bar [2333]
115
```
116
117
Multiple comma-separated `section` names may be specified in the `NODE_DEBUG`
118
environment variable: `NODE_DEBUG=fs,net,tls`.
119
120
## util.deprecate(fn, msg[, code])
121
<!-- YAML
122
added: v0.8.0
123
changes:
124
- version: v10.0.0
125
pr-url: https://github.com/nodejs/node/pull/16393
126
description: Deprecation warnings are only emitted once for each code.
127
-->
128
129
* `fn` {Function} The function that is being deprecated.
130
* `msg` {string} A warning message to display when the deprecated function is
131
invoked.
132
* `code` {string} A deprecation code. See the [list of deprecated APIs][] for a
133
list of codes.
134
* Returns: {Function} The deprecated function wrapped to emit a warning.
135
136
The `util.deprecate()` method wraps `fn` (which may be a function or class) in
137
such a way that it is marked as deprecated.
138
139
```js
140
const util = require('util');
141
142
exports.obsoleteFunction = util.deprecate(() => {
143
// Do something here.
144
}, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.');
145
```
146
147
When called, `util.deprecate()` will return a function that will emit a
148
`DeprecationWarning` using the [`'warning'`][] event. The warning will
149
be emitted and printed to `stderr` the first time the returned function is
150
called. After the warning is emitted, the wrapped function is called without
151
emitting a warning.
152
153
If the same optional `code` is supplied in multiple calls to `util.deprecate()`,
154
the warning will be emitted only once for that `code`.
155
156
```js
157
const util = require('util');
158
159
const fn1 = util.deprecate(someFunction, someMessage, 'DEP0001');
160
const fn2 = util.deprecate(someOtherFunction, someOtherMessage, 'DEP0001');
161
fn1(); // emits a deprecation warning with code DEP0001
162
fn2(); // does not emit a deprecation warning because it has the same code
163
```
164
165
If either the `--no-deprecation` or `--no-warnings` command line flags are
166
used, or if the `process.noDeprecation` property is set to `true` *prior* to
167
the first deprecation warning, the `util.deprecate()` method does nothing.
168
169
If the `--trace-deprecation` or `--trace-warnings` command line flags are set,
170
or the `process.traceDeprecation` property is set to `true`, a warning and a
171
stack trace are printed to `stderr` the first time the deprecated function is
172
called.
173
174
If the `--throw-deprecation` command line flag is set, or the
175
`process.throwDeprecation` property is set to `true`, then an exception will be
176
thrown when the deprecated function is called.
177
178
The `--throw-deprecation` command line flag and `process.throwDeprecation`
179
property take precedence over `--trace-deprecation` and
180
`process.traceDeprecation`.
181
182
## util.format(format[, ...args])
183
<!-- YAML
184
added: v0.5.3
185
changes:
186
- version: v8.4.0
187
pr-url: https://github.com/nodejs/node/pull/14558
188
description: The `%o` and `%O` specifiers are supported now.
189
-->
190
191
* `format` {string} A `printf`-like format string.
192
193
The `util.format()` method returns a formatted string using the first argument
194
as a `printf`-like format.
195
196
The first argument is a string containing zero or more *placeholder* tokens.
197
Each placeholder token is replaced with the converted value from the
198
corresponding argument. Supported placeholders are:
199
200
* `%s` - `String`.
201
* `%d` - `Number` (integer or floating point value).
202
* `%i` - Integer.
203
* `%f` - Floating point value.
204
* `%j` - JSON. Replaced with the string `'[Circular]'` if the argument
205
contains circular references.
206
* `%o` - `Object`. A string representation of an object
207
with generic JavaScript object formatting.
208
Similar to `util.inspect()` with options
209
`{ showHidden: true, showProxy: true }`. This will show the full object
210
including non-enumerable properties and proxies.
211
* `%O` - `Object`. A string representation of an object with generic JavaScript
212
object formatting. Similar to `util.inspect()` without options. This will show
213
the full object not including non-enumerable properties and proxies.
214
* `%%` - single percent sign (`'%'`). This does not consume an argument.
215
* Returns: {string} The formatted string
216
217
If the placeholder does not have a corresponding argument, the placeholder is
218
not replaced.
219
220
```js
221
util.format('%s:%s', 'foo');
222
// Returns: 'foo:%s'
223
```
224
225
If there are more arguments passed to the `util.format()` method than the number
226
of placeholders, the extra arguments are coerced into strings then concatenated
227
to the returned string, each delimited by a space. Excessive arguments whose
228
`typeof` is `'object'` or `'symbol'` (except `null`) will be transformed by
229
`util.inspect()`.
230
231
```js
232
util.format('%s:%s', 'foo', 'bar', 'baz'); // 'foo:bar baz'
233
```
234
235
If the first argument is not a string then `util.format()` returns
236
a string that is the concatenation of all arguments separated by spaces.
237
Each argument is converted to a string using `util.inspect()`.
238
239
```js
240
util.format(1, 2, 3); // '1 2 3'
241
```
242
243
If only one argument is passed to `util.format()`, it is returned as it is
244
without any formatting.
245
246
```js
247
util.format('%% %s'); // '%% %s'
248
```
249
250
Please note that `util.format()` is a synchronous method that is mainly
251
intended as a debugging tool. Some input values can have a significant
252
performance overhead that can block the event loop. Use this function
253
with care and never in a hot code path.
254
255
## util.formatWithOptions(inspectOptions, format[, ...args])
256
<!-- YAML
257
added: v10.0.0
258
-->
259
260
* `inspectOptions` {Object}
261
* `format` {string}
262
263
This function is identical to [`util.format()`][], except in that it takes
264
an `inspectOptions` argument which specifies options that are passed along to
265
[`util.inspect()`][].
266
267
```js
268
util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 });
269
// Returns 'See object { foo: 42 }', where `42` is colored as a number
270
// when printed to a terminal.
271
```
272
273
## util.getSystemErrorName(err)
274
<!-- YAML
275
added: v9.7.0
276
-->
277
278
* `err` {number}
279
* Returns: {string}
280
281
Returns the string name for a numeric error code that comes from a Node.js API.
282
The mapping between error codes and error names is platform-dependent.
283
See [Common System Errors][] for the names of common errors.
284
285
```js
286
fs.access('file/that/does/not/exist', (err) => {
287
const name = util.getSystemErrorName(err.errno);
288
console.error(name); // ENOENT
289
});
290
```
291
292
## util.inherits(constructor, superConstructor)
293
<!-- YAML
294
added: v0.3.0
295
changes:
296
- version: v5.0.0
297
pr-url: https://github.com/nodejs/node/pull/3455
298
description: The `constructor` parameter can refer to an ES6 class now.
299
-->
300
301
* `constructor` {Function}
302
* `superConstructor` {Function}
303
304
Usage of `util.inherits()` is discouraged. Please use the ES6 `class` and
305
`extends` keywords to get language level inheritance support. Also note
306
that the two styles are [semantically incompatible][].
307
308
Inherit the prototype methods from one [constructor][] into another. The
309
prototype of `constructor` will be set to a new object created from
310
`superConstructor`.
311
312
As an additional convenience, `superConstructor` will be accessible
313
through the `constructor.super_` property.
314
315
```js
316
const util = require('util');
317
const EventEmitter = require('events');
318
319
function MyStream() {
320
EventEmitter.call(this);
321
}
322
323
util.inherits(MyStream, EventEmitter);
324
325
MyStream.prototype.write = function(data) {
326
this.emit('data', data);
327
};
328
329
const stream = new MyStream();
330
331
console.log(stream instanceof EventEmitter); // true
332
console.log(MyStream.super_ === EventEmitter); // true
333
334
stream.on('data', (data) => {
335
console.log(`Received data: "${data}"`);
336
});
337
stream.write('It works!'); // Received data: "It works!"
338
```
339
340
ES6 example using `class` and `extends`:
341
342
```js
343
const EventEmitter = require('events');
344
345
class MyStream extends EventEmitter {
346
write(data) {
347
this.emit('data', data);
348
}
349
}
350
351
const stream = new MyStream();
352
353
stream.on('data', (data) => {
354
console.log(`Received data: "${data}"`);
355
});
356
stream.write('With ES6');
357
```
358
359
## util.inspect(object[, options])
360
<!-- YAML
361
added: v0.3.0
362
changes:
363
- version: REPLACEME
364
pr-url: https://github.com/nodejs/node/pull/22788
365
description: The `sorted` option is supported now.
366
- version: REPLACEME
367
pr-url: https://github.com/nodejs/node/pull/22756
368
description: The inspection output is now limited to about 128 MB. Data
369
above that size will not be fully inspected.
370
- version: v10.6.0
371
pr-url: https://github.com/nodejs/node/pull/20725
372
description: Inspecting linked lists and similar objects is now possible
373
up to the maximum call stack size.
374
- version: v10.0.0
375
pr-url: https://github.com/nodejs/node/pull/19259
376
description: The `WeakMap` and `WeakSet` entries can now be inspected
377
as well.
378
- version: v9.9.0
379
pr-url: https://github.com/nodejs/node/pull/17576
380
description: The `compact` option is supported now.
381
- version: v6.6.0
382
pr-url: https://github.com/nodejs/node/pull/8174
383
description: Custom inspection functions can now return `this`.
384
- version: v6.3.0
385
pr-url: https://github.com/nodejs/node/pull/7499
386
description: The `breakLength` option is supported now.
387
- version: v6.1.0
388
pr-url: https://github.com/nodejs/node/pull/6334
389
description: The `maxArrayLength` option is supported now; in particular,
390
long arrays are truncated by default.
391
- version: v6.1.0
392
pr-url: https://github.com/nodejs/node/pull/6465
393
description: The `showProxy` option is supported now.
394
-->
395
396
* `object` {any} Any JavaScript primitive or `Object`.
397
* `options` {Object}
398
* `showHidden` {boolean} If `true`, the `object`'s non-enumerable symbols and
399
properties will be included in the formatted result as well as [`WeakMap`][]
400
and [`WeakSet`][] entries. **Default:** `false`.
401
* `depth` {number} Specifies the number of times to recurse while formatting
402
the `object`. This is useful for inspecting large complicated objects. To
403
make it recurse up to the maximum call stack size pass `Infinity` or `null`.
404
**Default:** `2`.
405
* `colors` {boolean} If `true`, the output will be styled with ANSI color
406
codes. Colors are customizable, see [Customizing `util.inspect` colors][].
407
**Default:** `false`.
408
* `customInspect` {boolean} If `false`, then
409
`[util.inspect.custom](depth, opts)` functions will not be called.
410
**Default:** `true`.
411
* `showProxy` {boolean} If `true`, then objects and functions that are
412
`Proxy` objects will be introspected to show their `target` and `handler`
413
objects. **Default:** `false`.
414
<!--
415
TODO(BridgeAR): Deprecate `maxArrayLength` and replace it with
416
`maxEntries`.
417
-->
418
* `maxArrayLength` {integer} Specifies the maximum number of `Array`,
419
[`TypedArray`][], [`WeakMap`][] and [`WeakSet`][] elements to include when
420
formatting. Set to `null` or `Infinity` to show all elements. Set to `0` or
421
negative to show no elements. **Default:** `100`.
422
* `breakLength` {integer} The length at which an object's keys are split
423
across multiple lines. Set to `Infinity` to format an object as a single
424
line. **Default:** `60` for legacy compatibility.
425
* `compact` {boolean} Setting this to `false` changes the default indentation
426
to use a line break for each object key instead of lining up multiple
427
properties in one line. It will also break text that is above the
428
`breakLength` size into smaller and better readable chunks and indents
429
objects the same as arrays. Note that no text will be reduced below 16
430
characters, no matter the `breakLength` size. For more information, see the
431
example below. **Default:** `true`.
432
* `sorted` {boolean|Function} If set to `true` or a function, all properties
433
of an object and Set and Map entries will be sorted in the returned string.
434
If set to `true` the [default sort][] is going to be used. If set to a
435
function, it is used as a [compare function][].
436
* Returns: {string} The representation of passed object
437
438
The `util.inspect()` method returns a string representation of `object` that is
439
intended for debugging. The output of `util.inspect` may change at any time
440
and should not be depended upon programmatically. Additional `options` may be
441
passed that alter certain aspects of the formatted string.
442
`util.inspect()` will use the constructor's name and/or `@@toStringTag` to make
443
an identifiable tag for an inspected value.
444
445
```js
446
class Foo {
447
get [Symbol.toStringTag]() {
448
return 'bar';
449
}
450
}
451
452
class Bar {}
453
454
const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } });
455
456
util.inspect(new Foo()); // 'Foo [bar] {}'
457
util.inspect(new Bar()); // 'Bar {}'
458
util.inspect(baz); // '[foo] {}'
459
```
460
461
The following example inspects all properties of the `util` object:
462
463
```js
464
const util = require('util');
465
466
console.log(util.inspect(util, { showHidden: true, depth: null }));
467
```
468
469
The following example highlights the difference with the `compact` option:
470
471
```js
472
const util = require('util');
473
474
const o = {
475
a: [1, 2, [[
476
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do ' +
477
'eiusmod tempor incididunt ut labore et dolore magna aliqua.',
478
'test',
479
'foo']], 4],
480
b: new Map([['za', 1], ['zb', 'test']])
481
};
482
console.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 }));
483
484
// This will print
485
486
// { a:
487
// [ 1,
488
// 2,
489
// [ [ 'Lorem ipsum dolor sit amet, consectetur [...]', // A long line
490
// 'test',
491
// 'foo' ] ],
492
// 4 ],
493
// b: Map { 'za' => 1, 'zb' => 'test' } }
494
495
// Setting `compact` to false changes the output to be more reader friendly.
496
console.log(util.inspect(o, { compact: false, depth: 5, breakLength: 80 }));
497
498
// {
499
// a: [
500
// 1,
501
// 2,
502
// [
503
// [
504
// 'Lorem ipsum dolor sit amet, consectetur ' +
505
// 'adipiscing elit, sed do eiusmod tempor ' +
506
// 'incididunt ut labore et dolore magna ' +
507
// 'aliqua.,
508
// 'test',
509
// 'foo'
510
// ]
511
// ],
512
// 4
513
// ],
514
// b: Map {
515
// 'za' => 1,
516
// 'zb' => 'test'
517
// }
518
// }
519
520
// Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a
521
// single line.
522
// Reducing the `breakLength` will split the "Lorem ipsum" text in smaller
523
// chunks.
524
```
525
526
Using the `showHidden` option allows to inspect [`WeakMap`][] and [`WeakSet`][]
527
entries. If there are more entries than `maxArrayLength`, there is no guarantee
528
which entries are displayed. That means retrieving the same [`WeakSet`][]
529
entries twice might actually result in a different output. Besides this any item
530
might be collected at any point of time by the garbage collector if there is no
531
strong reference left to that object. Therefore there is no guarantee to get a
532
reliable output.
533
534
```js
535
const { inspect } = require('util');
536
537
const obj = { a: 1 };
538
const obj2 = { b: 2 };
539
const weakSet = new WeakSet([obj, obj2]);
540
541
console.log(inspect(weakSet, { showHidden: true }));
542
// WeakSet { { a: 1 }, { b: 2 } }
543
```
544
545
The `sorted` option makes sure the output is identical, no matter of the
546
properties insertion order:
547
548
```js
549
const { inspect } = require('util');
550
const assert = require('assert');
551
552
const o1 = {
553
b: [2, 3, 1],
554
a: '`a` comes before `b`',
555
c: new Set([2, 3, 1])
556
};
557
console.log(inspect(o1, { sorted: true }));
558
// { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set { 1, 2, 3 } }
559
console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) }));
560
// { c: Set { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' }
561
562
const o2 = {
563
c: new Set([2, 1, 3]),
564
a: '`a` comes before `b`',
565
b: [2, 3, 1]
566
};
567
assert.strict.equal(
568
inspect(o1, { sorted: true }),
569
inspect(o2, { sorted: true })
570
);
571
```
572
573
Please note that `util.inspect()` is a synchronous method that is mainly
574
intended as a debugging tool. Its maximum output length is limited to
575
approximately 128 MB and input values that result in output bigger than that
576
will not be inspected fully. Such values can have a significant performance
577
overhead that can block the event loop for a significant amount of time.
578
579
### Customizing `util.inspect` colors
580
581
<!-- type=misc -->
582
583
Color output (if enabled) of `util.inspect` is customizable globally
584
via the `util.inspect.styles` and `util.inspect.colors` properties.
585
586
`util.inspect.styles` is a map associating a style name to a color from
587
`util.inspect.colors`.
588
589
The default styles and associated colors are:
590
591
* `number` - `yellow`
592
* `boolean` - `yellow`
593
* `string` - `green`
594
* `date` - `magenta`
595
* `regexp` - `red`
596
* `null` - `bold`
597
* `undefined` - `grey`
598
* `special` - `cyan` (only applied to functions at this time)
599
* `name` - (no styling)
600
601
The predefined color codes are: `white`, `grey`, `black`, `blue`, `cyan`,
602
`green`, `magenta`, `red` and `yellow`. There are also `bold`, `italic`,
603
`underline` and `inverse` codes.
604
605
Color styling uses ANSI control codes that may not be supported on all
606
terminals.
607
608
### Custom inspection functions on Objects
609
610
<!-- type=misc -->
611
612
Objects may also define their own
613
[`[util.inspect.custom](depth, opts)`][util.inspect.custom] function,
614
which `util.inspect()` will invoke and use the result of when inspecting
615
the object:
616
617
```js
618
const util = require('util');
619
620
class Box {
621
constructor(value) {
622
this.value = value;
623
}
624
625
[util.inspect.custom](depth, options) {
626
if (depth < 0) {
627
return options.stylize('[Box]', 'special');
628
}
629
630
const newOptions = Object.assign({}, options, {
631
depth: options.depth === null ? null : options.depth - 1
632
});
633
634
// Five space padding because that's the size of "Box< ".
635
const padding = ' '.repeat(5);
636
const inner = util.inspect(this.value, newOptions)
637
.replace(/\n/g, `\n${padding}`);
638
return `${options.stylize('Box', 'special')}< ${inner} >`;
639
}
640
}
641
642
const box = new Box(true);
643
644
util.inspect(box);
645
// Returns: "Box< true >"
646
```
647
648
Custom `[util.inspect.custom](depth, opts)` functions typically return a string
649
but may return a value of any type that will be formatted accordingly by
650
`util.inspect()`.
651
652
```js
653
const util = require('util');
654
655
const obj = { foo: 'this will not show up in the inspect() output' };
656
obj[util.inspect.custom] = (depth) => {
657
return { bar: 'baz' };
658
};
659
660
util.inspect(obj);
661
// Returns: "{ bar: 'baz' }"
662
```
663
664
### util.inspect.custom
665
<!-- YAML
666
added: v6.6.0
667
changes:
668
- version: REPLACEME
669
pr-url: https://github.com/nodejs/node/pull/20857
670
description: This is now defined as a shared symbol.
671
-->
672
673
* {symbol} that can be used to declare custom inspect functions.
674
675
In addition to being accessible through `util.inspect.custom`, this
676
symbol is [registered globally][global symbol registry] and can be
677
accessed in any environment as `Symbol.for('nodejs.util.inspect.custom')`.
678
679
```js
680
const inspect = Symbol.for('nodejs.util.inspect.custom');
681
682
class Password {
683
constructor(value) {
684
this.value = value;
685
}
686
687
toString() {
688
return 'xxxxxxxx';
689
}
690
691
[inspect]() {
692
return `Password <${this.toString()}>`;
693
}
694
}
695
696
const password = new Password('r0sebud');
697
console.log(password);
698
// Prints Password <xxxxxxxx>
699
```
700
701
See [Custom inspection functions on Objects][] for more details.
702
703
### util.inspect.defaultOptions
704
<!-- YAML
705
added: v6.4.0
706
-->
707
708
The `defaultOptions` value allows customization of the default options used by
709
`util.inspect`. This is useful for functions like `console.log` or
710
`util.format` which implicitly call into `util.inspect`. It shall be set to an
711
object containing one or more valid [`util.inspect()`][] options. Setting
712
option properties directly is also supported.
713
714
```js
715
const util = require('util');
716
const arr = Array(101).fill(0);
717
718
console.log(arr); // logs the truncated array
719
util.inspect.defaultOptions.maxArrayLength = null;
720
console.log(arr); // logs the full array
721
```
722
723
## util.isDeepStrictEqual(val1, val2)
724
<!-- YAML
725
added: v9.0.0
726
-->
727
728
* `val1` {any}
729
* `val2` {any}
730
* Returns: {boolean}
731
732
Returns `true` if there is deep strict equality between `val1` and `val2`.
733
Otherwise, returns `false`.
734
735
See [`assert.deepStrictEqual()`][] for more information about deep strict
736
equality.
737
738
## util.promisify(original)
739
<!-- YAML
740
added: v8.0.0
741
-->
742
743
* `original` {Function}
744
* Returns: {Function}
745
746
Takes a function following the common error-first callback style, i.e. taking
747
an `(err, value) => ...` callback as the last argument, and returns a version
748
that returns promises.
749
750
```js
751
const util = require('util');
752
const fs = require('fs');
753
754
const stat = util.promisify(fs.stat);
755
stat('.').then((stats) => {
756
// Do something with `stats`
757
}).catch((error) => {
758
// Handle the error.
759
});
760
```
761
762
Or, equivalently using `async function`s:
763
764
```js
765
const util = require('util');
766
const fs = require('fs');
767
768
const stat = util.promisify(fs.stat);
769
770
async function callStat() {
771
const stats = await stat('.');
772
console.log(`This directory is owned by ${stats.uid}`);
773
}
774
```
775
776
If there is an `original[util.promisify.custom]` property present, `promisify`
777
will return its value, see [Custom promisified functions][].
778
779
`promisify()` assumes that `original` is a function taking a callback as its
780
final argument in all cases. If `original` is not a function, `promisify()`
781
will throw an error. If `original` is a function but its last argument is not
782
an error-first callback, it will still be passed an error-first
783
callback as its last argument.
784
785
### Custom promisified functions
786
787
Using the `util.promisify.custom` symbol one can override the return value of
788
[`util.promisify()`][]:
789
790
```js
791
const util = require('util');
792
793
function doSomething(foo, callback) {
794
// ...
795
}
796
797
doSomething[util.promisify.custom] = (foo) => {
798
return getPromiseSomehow();
799
};
800
801
const promisified = util.promisify(doSomething);
802
console.log(promisified === doSomething[util.promisify.custom]);
803
// prints 'true'
804
```
805
806
This can be useful for cases where the original function does not follow the
807
standard format of taking an error-first callback as the last argument.
808
809
For example, with a function that takes in
810
`(foo, onSuccessCallback, onErrorCallback)`:
811
812
```js
813
doSomething[util.promisify.custom] = (foo) => {
814
return new Promise((resolve, reject) => {
815
doSomething(foo, resolve, reject);
816
});
817
};
818
```
819
If `promisify.custom` is defined but is not a function, `promisify()` will
820
throw an error.
821
822
### util.promisify.custom
823
<!-- YAML
824
added: v8.0.0
825
-->
826
827
* {symbol} that can be used to declare custom promisified variants of functions,
828
see [Custom promisified functions][].
829
830
## Class: util.TextDecoder
831
<!-- YAML
832
added: v8.3.0
833
-->
834
835
An implementation of the [WHATWG Encoding Standard][] `TextDecoder` API.
836
837
```js
838
const decoder = new TextDecoder('shift_jis');
839
let string = '';
840
let buffer;
841
while (buffer = getNextChunkSomehow()) {
842
string += decoder.decode(buffer, { stream: true });
843
}
844
string += decoder.decode(); // end-of-stream
845
```
846
847
### WHATWG Supported Encodings
848
849
Per the [WHATWG Encoding Standard][], the encodings supported by the
850
`TextDecoder` API are outlined in the tables below. For each encoding,
851
one or more aliases may be used.
852
853
Different Node.js build configurations support different sets of encodings.
854
While a very basic set of encodings is supported even on Node.js builds without
855
ICU enabled, support for some encodings is provided only when Node.js is built
856
with ICU and using the full ICU data (see [Internationalization][]).
857
858
#### Encodings Supported Without ICU
859
860
| Encoding | Aliases |
861
| ----------- | --------------------------------- |
862
| `'utf-8'` | `'unicode-1-1-utf-8'`, `'utf8'` |
863
| `'utf-16le'` | `'utf-16'` |
864
865
#### Encodings Supported by Default (With ICU)
866
867
| Encoding | Aliases |
868
| ----------- | --------------------------------- |
869
| `'utf-8'` | `'unicode-1-1-utf-8'`, `'utf8'` |
870
| `'utf-16le'` | `'utf-16'` |
871
| `'utf-16be'` | |
872
873
#### Encodings Requiring Full ICU Data
874
875
| Encoding | Aliases |
876
| ----------------- | -------------------------------- |
877
| `'ibm866'` | `'866'`, `'cp866'`, `'csibm866'` |
878
| `'iso-8859-2'` | `'csisolatin2'`, `'iso-ir-101'`, `'iso8859-2'`, `'iso88592'`, `'iso_8859-2'`, `'iso_8859-2:1987'`, `'l2'`, `'latin2'` |
879
| `'iso-8859-3'` | `'csisolatin3'`, `'iso-ir-109'`, `'iso8859-3'`, `'iso88593'`, `'iso_8859-3'`, `'iso_8859-3:1988'`, `'l3'`, `'latin3'` |
880
| `'iso-8859-4'` | `'csisolatin4'`, `'iso-ir-110'`, `'iso8859-4'`, `'iso88594'`, `'iso_8859-4'`, `'iso_8859-4:1988'`, `'l4'`, `'latin4'` |
881
| `'iso-8859-5'` | `'csisolatincyrillic'`, `'cyrillic'`, `'iso-ir-144'`, `'iso8859-5'`, `'iso88595'`, `'iso_8859-5'`, `'iso_8859-5:1988'` |
882
| `'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'` |
883
| `'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'` |
884
| `'iso-8859-8'` | `'csiso88598e'`, `'csisolatinhebrew'`, `'hebrew'`, `'iso-8859-8-e'`, `'iso-ir-138'`, `'iso8859-8'`, `'iso88598'`, `'iso_8859-8'`, `'iso_8859-8:1988'`, `'visual'` |
885
| `'iso-8859-8-i'` | `'csiso88598i'`, `'logical'` |
886
| `'iso-8859-10'` | `'csisolatin6'`, `'iso-ir-157'`, `'iso8859-10'`, `'iso885910'`, `'l6'`, `'latin6'` |
887
| `'iso-8859-13'` | `'iso8859-13'`, `'iso885913'` |
888
| `'iso-8859-14'` | `'iso8859-14'`, `'iso885914'` |
889
| `'iso-8859-15'` | `'csisolatin9'`, `'iso8859-15'`, `'iso885915'`, `'iso_8859-15'`, `'l9'` |
890
| `'koi8-r'` | `'cskoi8r'`, `'koi'`, `'koi8'`, `'koi8_r'` |
891
| `'koi8-u'` | `'koi8-ru'` |
892
| `'macintosh'` | `'csmacintosh'`, `'mac'`, `'x-mac-roman'` |
893
| `'windows-874'` | `'dos-874'`, `'iso-8859-11'`, `'iso8859-11'`, `'iso885911'`, `'tis-620'` |
894
| `'windows-1250'` | `'cp1250'`, `'x-cp1250'` |
895
| `'windows-1251'` | `'cp1251'`, `'x-cp1251'` |
896
| `'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'` |
897
| `'windows-1253'` | `'cp1253'`, `'x-cp1253'` |
898
| `'windows-1254'` | `'cp1254'`, `'csisolatin5'`, `'iso-8859-9'`, `'iso-ir-148'`, `'iso8859-9'`, `'iso88599'`, `'iso_8859-9'`, `'iso_8859-9:1989'`, `'l5'`, `'latin5'`, `'x-cp1254'` |
899
| `'windows-1255'` | `'cp1255'`, `'x-cp1255'` |
900
| `'windows-1256'` | `'cp1256'`, `'x-cp1256'` |
901
| `'windows-1257'` | `'cp1257'`, `'x-cp1257'` |
902
| `'windows-1258'` | `'cp1258'`, `'x-cp1258'` |
903
| `'x-mac-cyrillic'` | `'x-mac-ukrainian'` |
904
| `'gbk'` | `'chinese'`, `'csgb2312'`, `'csiso58gb231280'`, `'gb2312'`, `'gb_2312'`, `'gb_2312-80'`, `'iso-ir-58'`, `'x-gbk'` |
905
| `'gb18030'` | |
906
| `'big5'` | `'big5-hkscs'`, `'cn-big5'`, `'csbig5'`, `'x-x-big5'` |
907
| `'euc-jp'` | `'cseucpkdfmtjapanese'`, `'x-euc-jp'` |
908
| `'iso-2022-jp'` | `'csiso2022jp'` |
909
| `'shift_jis'` | `'csshiftjis'`, `'ms932'`, `'ms_kanji'`, `'shift-jis'`, `'sjis'`, `'windows-31j'`, `'x-sjis'` |
910
| `'euc-kr'` | `'cseuckr'`, `'csksc56011987'`, `'iso-ir-149'`, `'korean'`, `'ks_c_5601-1987'`, `'ks_c_5601-1989'`, `'ksc5601'`, `'ksc_5601'`, `'windows-949'` |
911
912
The `'iso-8859-16'` encoding listed in the [WHATWG Encoding Standard][]
913
is not supported.
914
915
### new TextDecoder([encoding[, options]])
916
<!-- YAML
917
added: v8.3.0
918
changes:
919
- version: REPLACEME
920
pr-url: REPLACEME
921
description: The class is now available on the global object.
922
-->
923
924
* `encoding` {string} Identifies the `encoding` that this `TextDecoder` instance
925
supports. **Default:** `'utf-8'`.
926
* `options` {Object}
927
* `fatal` {boolean} `true` if decoding failures are fatal. This option is only
928
supported when ICU is enabled (see [Internationalization][]). **Default:**
929
`false`.
930
* `ignoreBOM` {boolean} When `true`, the `TextDecoder` will include the byte
931
order mark in the decoded result. When `false`, the byte order mark will
932
be removed from the output. This option is only used when `encoding` is
933
`'utf-8'`, `'utf-16be'` or `'utf-16le'`. **Default:** `false`.
934
935
Creates an new `TextDecoder` instance. The `encoding` may specify one of the
936
supported encodings or an alias.
937
938
The `TextDecoder` class is also available on the global object.
939
940
### textDecoder.decode([input[, options]])
941
942
* `input` {ArrayBuffer|DataView|TypedArray} An `ArrayBuffer`, `DataView` or
943
`TypedArray` instance containing the encoded data.
944
* `options` {Object}
945
* `stream` {boolean} `true` if additional chunks of data are expected.
946
**Default:** `false`.
947
* Returns: {string}
948
949
Decodes the `input` and returns a string. If `options.stream` is `true`, any
950
incomplete byte sequences occurring at the end of the `input` are buffered
951
internally and emitted after the next call to `textDecoder.decode()`.
952
953
If `textDecoder.fatal` is `true`, decoding errors that occur will result in a
954
`TypeError` being thrown.
955
956
### textDecoder.encoding
957
958
* {string}
959
960
The encoding supported by the `TextDecoder` instance.
961
962
### textDecoder.fatal
963
964
* {boolean}
965
966
The value will be `true` if decoding errors result in a `TypeError` being
967
thrown.
968
969
### textDecoder.ignoreBOM
970
971
* {boolean}
972
973
The value will be `true` if the decoding result will include the byte order
974
mark.
975
976
## Class: util.TextEncoder
977
<!-- YAML
978
added: v8.3.0
979
changes:
980
- version: REPLACEME
981
pr-url: REPLACEME
982
description: The class is now available on the global object.
983
-->
984
985
An implementation of the [WHATWG Encoding Standard][] `TextEncoder` API. All
986
instances of `TextEncoder` only support UTF-8 encoding.
987
988
```js
989
const encoder = new TextEncoder();
990
const uint8array = encoder.encode('this is some data');
991
```
992
993
The `TextEncoder` class is also available on the global object.
994
995
### textEncoder.encode([input])
996
997
* `input` {string} The text to encode. **Default:** an empty string.
998
* Returns: {Uint8Array}
999
1000
UTF-8 encodes the `input` string and returns a `Uint8Array` containing the