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