Skip to content

Latest commit

Β 

History

History
2209 lines (1716 loc) Β· 60.6 KB

File metadata and controls

2209 lines (1716 loc) Β· 60.6 KB
Β 
Feb 10, 2017
Feb 10, 2017
1
# Util
Oct 28, 2010
Oct 28, 2010
2
Aug 28, 2017
Aug 28, 2017
3
<!--introduced_in=v0.10.0-->
4
Aug 4, 2016
Aug 4, 2016
5
> Stability: 2 - Stable
Mar 4, 2012
Mar 4, 2012
6
May 23, 2016
May 23, 2016
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:
Oct 28, 2010
Oct 28, 2010
10
May 23, 2016
May 23, 2016
11
```js
12
const util = require('util');
13
```
Nov 13, 2015
Nov 13, 2015
14
Jun 11, 2017
Jun 11, 2017
15
## util.callbackify(original)
16
<!-- YAML
Jul 19, 2017
Jul 19, 2017
17
added: v8.2.0
Jun 11, 2017
Jun 11, 2017
18
-->
19
20
* `original` {Function} An `async` function
21
* Returns: {Function} a callback style function
22
May 2, 2018
May 2, 2018
23
Takes an `async` function (or a function that returns a `Promise`) and returns a
Dec 17, 2017
Dec 17, 2017
24
function following the error-first callback style, i.e. taking
May 2, 2018
May 2, 2018
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`
Dec 17, 2017
Dec 17, 2017
27
resolved), and the second argument will be the resolved value.
Jun 11, 2017
Jun 11, 2017
28
29
```js
30
const util = require('util');
31
32
async function fn() {
Dec 1, 2017
Dec 1, 2017
33
return 'hello world';
Jun 11, 2017
Jun 11, 2017
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
Feb 8, 2018
Feb 8, 2018
49
The callback is executed asynchronously, and will have a limited stack trace.
Jun 11, 2017
Jun 11, 2017
50
If the callback throws, the process will emit an [`'uncaughtException'`][]
51
event, and if not handled will exit.
52
Feb 8, 2018
Feb 8, 2018
53
Since `null` has a special meaning as the first argument to a callback, if a
Jun 11, 2017
Jun 11, 2017
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
May 2, 2018
May 2, 2018
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
```
Jun 11, 2017
Jun 11, 2017
70
May 21, 2013
May 21, 2013
71
## util.debuglog(section)
Aug 23, 2016
Aug 23, 2016
72
<!-- YAML
73
added: v0.11.3
74
-->
May 21, 2013
May 21, 2013
75
Mar 2, 2017
Mar 2, 2017
76
* `section` {string} A string identifying the portion of the application for
May 23, 2016
May 23, 2016
77
which the `debuglog` function is being created.
May 21, 2013
May 21, 2013
78
* Returns: {Function} The logging function
79
May 23, 2016
May 23, 2016
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`
Apr 4, 2018
Apr 4, 2018
82
environment variable. If the `section` name appears within the value of that
May 29, 2016
May 29, 2016
83
environment variable, then the returned function operates similar to
Apr 4, 2018
Apr 4, 2018
84
[`console.error()`][]. If not, then the returned function is a no-op.
May 21, 2013
May 21, 2013
85
Jan 21, 2016
Jan 21, 2016
86
```js
May 29, 2016
May 29, 2016
87
const util = require('util');
May 23, 2016
May 23, 2016
88
const debuglog = util.debuglog('foo');
May 21, 2013
May 21, 2013
89
May 23, 2016
May 23, 2016
90
debuglog('hello from foo [%d]', 123);
May 21, 2013
May 21, 2013
91
```
92
93
If this program is run with `NODE_DEBUG=foo` in the environment, then
94
it will output something like:
95
Jul 14, 2016
Jul 14, 2016
96
```txt
Jan 21, 2016
Jan 21, 2016
97
FOO 3245: hello from foo [123]
98
```
May 21, 2013
May 21, 2013
99
Apr 4, 2018
Apr 4, 2018
100
where `3245` is the process id. If it is not run with that
May 21, 2013
May 21, 2013
101
environment variable set, then it will not print anything.
102
Feb 23, 2018
Feb 23, 2018
103
The `section` supports wildcard also:
Dec 15, 2017
Dec 15, 2017
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
Feb 23, 2018
Feb 23, 2018
111
if it is run with `NODE_DEBUG=foo*` in the environment, then it will output
112
something like:
Dec 15, 2017
Dec 15, 2017
113
```txt
114
FOO-BAR 3257: hi there, it's foo-bar [2333]
115
```
116
May 23, 2016
May 23, 2016
117
Multiple comma-separated `section` names may be specified in the `NODE_DEBUG`
Feb 23, 2018
Feb 23, 2018
118
environment variable: `NODE_DEBUG=fs,net,tls`.
Oct 28, 2010
Oct 28, 2010
119
Nov 17, 2017
Nov 17, 2017
120
## util.deprecate(fn, msg[, code])
Aug 23, 2016
Aug 23, 2016
121
<!-- YAML
122
added: v0.8.0
Nov 17, 2017
Nov 17, 2017
123
changes:
Apr 24, 2018
Apr 24, 2018
124
- version: v10.0.0
Nov 17, 2017
Nov 17, 2017
125
pr-url: https://github.com/nodejs/node/pull/16393
Nov 17, 2017
Nov 17, 2017
126
description: Deprecation warnings are only emitted once for each code.
Aug 23, 2016
Aug 23, 2016
127
-->
Nov 13, 2015
Nov 13, 2015
128
Nov 17, 2017
Nov 17, 2017
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.
Nov 13, 2015
Nov 13, 2015
138
Jan 21, 2016
Jan 21, 2016
139
```js
140
const util = require('util');
Nov 13, 2015
Nov 13, 2015
141
Dec 6, 2017
Dec 6, 2017
142
exports.obsoleteFunction = util.deprecate(() => {
Nov 17, 2017
Nov 17, 2017
143
// Do something here.
144
}, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.');
Jan 21, 2016
Jan 21, 2016
145
```
Nov 13, 2015
Nov 13, 2015
146
May 29, 2016
May 29, 2016
147
When called, `util.deprecate()` will return a function that will emit a
Apr 12, 2018
Apr 12, 2018
148
`DeprecationWarning` using the [`'warning'`][] event. The warning will
Nov 17, 2017
Nov 17, 2017
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
```
Nov 13, 2015
Nov 13, 2015
164
May 23, 2016
May 23, 2016
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.
Nov 13, 2015
Nov 13, 2015
168
May 23, 2016
May 23, 2016
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.
Nov 13, 2015
Nov 13, 2015
173
May 23, 2016
May 23, 2016
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.
Nov 13, 2015
Nov 13, 2015
177
May 23, 2016
May 23, 2016
178
The `--throw-deprecation` command line flag and `process.throwDeprecation`
179
property take precedence over `--trace-deprecation` and
180
`process.traceDeprecation`.
Nov 13, 2015
Nov 13, 2015
181
Sep 14, 2016
Sep 14, 2016
182
## util.format(format[, ...args])
Aug 23, 2016
Aug 23, 2016
183
<!-- YAML
184
added: v0.5.3
Aug 13, 2017
Aug 13, 2017
185
changes:
Aug 15, 2017
Aug 15, 2017
186
- version: v8.4.0
Aug 13, 2017
Aug 13, 2017
187
pr-url: https://github.com/nodejs/node/pull/14558
188
description: The `%o` and `%O` specifiers are supported now.
Aug 23, 2016
Aug 23, 2016
189
-->
Aug 5, 2011
Aug 5, 2011
190
Mar 2, 2017
Mar 2, 2017
191
* `format` {string} A `printf`-like format string.
May 23, 2016
May 23, 2016
192
193
The `util.format()` method returns a formatted string using the first argument
194
as a `printf`-like format.
Aug 5, 2011
Aug 5, 2011
195
May 23, 2016
May 23, 2016
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:
Aug 5, 2011
Aug 5, 2011
199
May 2, 2018
May 2, 2018
200
* `%s` - `String`.
201
* `%d` - `Number` (integer or floating point value).
Mar 29, 2017
Mar 29, 2017
202
* `%i` - Integer.
203
* `%f` - Floating point value.
Apr 4, 2018
Apr 4, 2018
204
* `%j` - JSON. Replaced with the string `'[Circular]'` if the argument
Mar 8, 2015
Mar 8, 2015
205
contains circular references.
May 2, 2018
May 2, 2018
206
* `%o` - `Object`. A string representation of an object
Aug 4, 2017
Aug 4, 2017
207
with generic JavaScript object formatting.
Feb 23, 2018
Feb 23, 2018
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.
May 2, 2018
May 2, 2018
211
* `%O` - `Object`. A string representation of an object with generic JavaScript
Jan 16, 2018
Jan 16, 2018
212
object formatting. Similar to `util.inspect()` without options. This will show
213
the full object not including non-enumerable properties and proxies.
Aug 5, 2011
Aug 5, 2011
214
* `%%` - single percent sign (`'%'`). This does not consume an argument.
Feb 16, 2018
Feb 16, 2018
215
* Returns: {string} The formatted string
Aug 5, 2011
Aug 5, 2011
216
Aug 8, 2011
Aug 8, 2011
217
If the placeholder does not have a corresponding argument, the placeholder is
218
not replaced.
Aug 5, 2011
Aug 5, 2011
219
Jan 21, 2016
Jan 21, 2016
220
```js
May 23, 2016
May 23, 2016
221
util.format('%s:%s', 'foo');
Nov 16, 2016
Nov 16, 2016
222
// Returns: 'foo:%s'
Jan 21, 2016
Jan 21, 2016
223
```
Aug 5, 2011
Aug 5, 2011
224
Jul 4, 2017
Jul 4, 2017
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()`.
Aug 5, 2011
Aug 5, 2011
230
Jan 21, 2016
Jan 21, 2016
231
```js
232
util.format('%s:%s', 'foo', 'bar', 'baz'); // 'foo:bar baz'
233
```
Aug 5, 2011
Aug 5, 2011
234
Jul 4, 2017
Jul 4, 2017
235
If the first argument is not a string then `util.format()` returns
May 23, 2016
May 23, 2016
236
a string that is the concatenation of all arguments separated by spaces.
237
Each argument is converted to a string using `util.inspect()`.
Aug 5, 2011
Aug 5, 2011
238
Jan 21, 2016
Jan 21, 2016
239
```js
240
util.format(1, 2, 3); // '1 2 3'
241
```
Aug 5, 2011
Aug 5, 2011
242
Apr 13, 2017
Apr 13, 2017
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
Dec 21, 2017
Dec 21, 2017
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
Apr 12, 2018
Apr 12, 2018
255
## util.formatWithOptions(inspectOptions, format[, ...args])
256
<!-- YAML
Apr 24, 2018
Apr 24, 2018
257
added: v10.0.0
Apr 12, 2018
Apr 12, 2018
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 });
Apr 12, 2018
Apr 12, 2018
269
// Returns 'See object { foo: 42 }', where `42` is colored as a number
270
// when printed to a terminal.
Apr 12, 2018
Apr 12, 2018
271
```
272
Jan 20, 2018
Jan 20, 2018
273
## util.getSystemErrorName(err)
274
<!-- YAML
Mar 1, 2018
Mar 1, 2018
275
added: v9.7.0
Jan 20, 2018
Jan 20, 2018
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
Nov 13, 2015
Nov 13, 2015
292
## util.inherits(constructor, superConstructor)
Aug 23, 2016
Aug 23, 2016
293
<!-- YAML
294
added: v0.3.0
Feb 24, 2017
Feb 24, 2017
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.
Aug 23, 2016
Aug 23, 2016
299
-->
Aug 5, 2011
Aug 5, 2011
300
Jul 15, 2018
Jul 15, 2018
301
* `constructor` {Function}
302
* `superConstructor` {Function}
303
Feb 8, 2018
Feb 8, 2018
304
Usage of `util.inherits()` is discouraged. Please use the ES6 `class` and
305
`extends` keywords to get language level inheritance support. Also note
May 25, 2017
May 25, 2017
306
that the two styles are [semantically incompatible][].
May 9, 2016
May 9, 2016
307
Apr 4, 2018
Apr 4, 2018
308
Inherit the prototype methods from one [constructor][] into another. The
Nov 16, 2015
Nov 16, 2015
309
prototype of `constructor` will be set to a new object created from
310
`superConstructor`.
Oct 28, 2010
Oct 28, 2010
311
Nov 13, 2015
Nov 13, 2015
312
As an additional convenience, `superConstructor` will be accessible
313
through the `constructor.super_` property.
Oct 28, 2010
Oct 28, 2010
314
Jan 21, 2016
Jan 21, 2016
315
```js
316
const util = require('util');
317
const EventEmitter = require('events');
Nov 13, 2015
Nov 13, 2015
318
Jan 21, 2016
Jan 21, 2016
319
function MyStream() {
Jul 15, 2016
Jul 15, 2016
320
EventEmitter.call(this);
Jan 21, 2016
Jan 21, 2016
321
}
Nov 13, 2015
Nov 13, 2015
322
Jan 21, 2016
Jan 21, 2016
323
util.inherits(MyStream, EventEmitter);
Nov 13, 2015
Nov 13, 2015
324
Jan 21, 2016
Jan 21, 2016
325
MyStream.prototype.write = function(data) {
Jul 15, 2016
Jul 15, 2016
326
this.emit('data', data);
327
};
Nov 13, 2015
Nov 13, 2015
328
May 29, 2016
May 29, 2016
329
const stream = new MyStream();
Nov 13, 2015
Nov 13, 2015
330
Jan 21, 2016
Jan 21, 2016
331
console.log(stream instanceof EventEmitter); // true
332
console.log(MyStream.super_ === EventEmitter); // true
Nov 13, 2015
Nov 13, 2015
333
Jan 21, 2016
Jan 21, 2016
334
stream.on('data', (data) => {
335
console.log(`Received data: "${data}"`);
Jul 15, 2016
Jul 15, 2016
336
});
Jan 21, 2016
Jan 21, 2016
337
stream.write('It works!'); // Received data: "It works!"
338
```
Oct 28, 2010
Oct 28, 2010
339
May 2, 2018
May 2, 2018
340
ES6 example using `class` and `extends`:
Aug 21, 2016
Aug 21, 2016
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
Sep 25, 2014
Sep 25, 2014
359
## util.inspect(object[, options])
Aug 23, 2016
Aug 23, 2016
360
<!-- YAML
361
added: v0.3.0
Feb 24, 2017
Feb 24, 2017
362
changes:
Sep 19, 2018
Sep 19, 2018
363
- version: REPLACEME
364
pr-url: https://github.com/nodejs/node/pull/22788
365
description: The `sorted` option is supported now.
Sep 13, 2018
Sep 13, 2018
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.
Jul 4, 2018
Jul 4, 2018
370
- version: v10.6.0
371
pr-url: https://github.com/nodejs/node/pull/20725
Jun 25, 2018
Jun 25, 2018
372
description: Inspecting linked lists and similar objects is now possible
373
up to the maximum call stack size.
Apr 24, 2018
Apr 24, 2018
374
- version: v10.0.0
Mar 25, 2018
Mar 25, 2018
375
pr-url: https://github.com/nodejs/node/pull/19259
May 2, 2018
May 2, 2018
376
description: The `WeakMap` and `WeakSet` entries can now be inspected
377
as well.
Mar 21, 2018
Mar 21, 2018
378
- version: v9.9.0
Feb 4, 2018
Feb 4, 2018
379
pr-url: https://github.com/nodejs/node/pull/17576
Dec 21, 2017
Dec 21, 2017
380
description: The `compact` option is supported now.
Feb 24, 2017
Feb 24, 2017
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.
Aug 23, 2016
Aug 23, 2016
394
-->
Oct 28, 2010
Oct 28, 2010
395
May 2, 2018
May 2, 2018
396
* `object` {any} Any JavaScript primitive or `Object`.
May 23, 2016
May 23, 2016
397
* `options` {Object}
May 29, 2016
May 29, 2016
398
* `showHidden` {boolean} If `true`, the `object`'s non-enumerable symbols and
Mar 25, 2018
Mar 25, 2018
399
properties will be included in the formatted result as well as [`WeakMap`][]
Apr 4, 2018
Apr 4, 2018
400
and [`WeakSet`][] entries. **Default:** `false`.
May 11, 2018
May 11, 2018
401
* `depth` {number} Specifies the number of times to recurse while formatting
Jun 25, 2018
Jun 25, 2018
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`.
May 23, 2016
May 23, 2016
405
* `colors` {boolean} If `true`, the output will be styled with ANSI color
Apr 4, 2018
Apr 4, 2018
406
codes. Colors are customizable, see [Customizing `util.inspect` colors][].
407
**Default:** `false`.
May 19, 2018
May 19, 2018
408
* `customInspect` {boolean} If `false`, then
409
`[util.inspect.custom](depth, opts)` functions will not be called.
410
**Default:** `true`.
May 23, 2016
May 23, 2016
411
* `showProxy` {boolean} If `true`, then objects and functions that are
May 29, 2016
May 29, 2016
412
`Proxy` objects will be introspected to show their `target` and `handler`
Apr 4, 2018
Apr 4, 2018
413
objects. **Default:** `false`.
Mar 25, 2018
Mar 25, 2018
414
<!--
415
TODO(BridgeAR): Deprecate `maxArrayLength` and replace it with
416
`maxEntries`.
417
-->
Sep 13, 2018
Sep 13, 2018
418
* `maxArrayLength` {integer} Specifies the maximum number of `Array`,
Mar 25, 2018
Mar 25, 2018
419
[`TypedArray`][], [`WeakMap`][] and [`WeakSet`][] elements to include when
Apr 4, 2018
Apr 4, 2018
420
formatting. Set to `null` or `Infinity` to show all elements. Set to `0` or
421
negative to show no elements. **Default:** `100`.
Sep 13, 2018
Sep 13, 2018
422
* `breakLength` {integer} The length at which an object's keys are split
Jul 5, 2016
Jul 5, 2016
423
across multiple lines. Set to `Infinity` to format an object as a single
Apr 4, 2018
Apr 4, 2018
424
line. **Default:** `60` for legacy compatibility.
Dec 21, 2017
Dec 21, 2017
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
Apr 4, 2018
Apr 4, 2018
431
example below. **Default:** `true`.
Sep 19, 2018
Sep 19, 2018
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][].
Feb 16, 2018
Feb 16, 2018
436
* Returns: {string} The representation of passed object
May 23, 2016
May 23, 2016
437
438
The `util.inspect()` method returns a string representation of `object` that is
Dec 12, 2017
Dec 12, 2017
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.
Feb 23, 2018
Feb 23, 2018
442
`util.inspect()` will use the constructor's name and/or `@@toStringTag` to make
443
an identifiable tag for an inspected value.
Dec 1, 2017
Dec 1, 2017
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
```
May 23, 2016
May 23, 2016
460
May 11, 2018
May 11, 2018
461
The following example inspects all properties of the `util` object:
Oct 28, 2010
Oct 28, 2010
462
Jan 21, 2016
Jan 21, 2016
463
```js
464
const util = require('util');
Oct 28, 2010
Oct 28, 2010
465
May 11, 2018
May 11, 2018
466
console.log(util.inspect(util, { showHidden: true, depth: null }));
Jan 21, 2016
Jan 21, 2016
467
```
Oct 28, 2010
Oct 28, 2010
468
Dec 21, 2017
Dec 21, 2017
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
};
May 11, 2018
May 11, 2018
482
console.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 }));
Dec 21, 2017
Dec 21, 2017
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.
May 11, 2018
May 11, 2018
496
console.log(util.inspect(o, { compact: false, depth: 5, breakLength: 80 }));
Dec 21, 2017
Dec 21, 2017
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
Mar 25, 2018
Mar 25, 2018
526
Using the `showHidden` option allows to inspect [`WeakMap`][] and [`WeakSet`][]
527
entries. If there are more entries than `maxArrayLength`, there is no guarantee
Apr 7, 2018
Apr 7, 2018
528
which entries are displayed. That means retrieving the same [`WeakSet`][]
Mar 25, 2018
Mar 25, 2018
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
Sep 19, 2018
Sep 19, 2018
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 } }
Sep 22, 2018
Sep 22, 2018
559
console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) }));
Sep 19, 2018
Sep 19, 2018
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
Dec 21, 2017
Dec 21, 2017
573
Please note that `util.inspect()` is a synchronous method that is mainly
Sep 13, 2018
Sep 13, 2018
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.
Dec 21, 2017
Dec 21, 2017
578
Jul 17, 2012
Jul 17, 2012
579
### Customizing `util.inspect` colors
580
May 21, 2013
May 21, 2013
581
<!-- type=misc -->
582
Jul 17, 2012
Jul 17, 2012
583
Color output (if enabled) of `util.inspect` is customizable globally
May 23, 2016
May 23, 2016
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.
Jul 17, 2012
Jul 17, 2012
607
Aug 25, 2016
Aug 25, 2016
608
### Custom inspection functions on Objects
Mar 12, 2013
Mar 12, 2013
609
May 21, 2013
May 21, 2013
610
<!-- type=misc -->
611
Sep 15, 2018
Sep 15, 2018
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:
Oct 5, 2012
Oct 5, 2012
616
Jan 21, 2016
Jan 21, 2016
617
```js
618
const util = require('util');
Oct 5, 2012
Oct 5, 2012
619
Oct 26, 2016
Oct 26, 2016
620
class Box {
621
constructor(value) {
622
this.value = value;
623
}
624
Oct 2, 2017
Oct 2, 2017
625
[util.inspect.custom](depth, options) {
Oct 26, 2016
Oct 26, 2016
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);
Apr 24, 2017
Apr 24, 2017
636
const inner = util.inspect(this.value, newOptions)
Jun 1, 2017
Jun 1, 2017
637
.replace(/\n/g, `\n${padding}`);
638
return `${options.stylize('Box', 'special')}< ${inner} >`;
Oct 26, 2016
Oct 26, 2016
639
}
640
}
641
642
const box = new Box(true);
Oct 5, 2012
Oct 5, 2012
643
Oct 26, 2016
Oct 26, 2016
644
util.inspect(box);
Nov 16, 2016
Nov 16, 2016
645
// Returns: "Box< true >"
Jan 21, 2016
Jan 21, 2016
646
```
Oct 5, 2012
Oct 5, 2012
647
Aug 25, 2016
Aug 25, 2016
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
May 23, 2016
May 23, 2016
650
`util.inspect()`.
Mar 12, 2013
Mar 12, 2013
651
Jan 21, 2016
Jan 21, 2016
652
```js
May 29, 2016
May 29, 2016
653
const util = require('util');
654
Aug 25, 2016
Aug 25, 2016
655
const obj = { foo: 'this will not show up in the inspect() output' };
Nov 26, 2017
Nov 26, 2017
656
obj[util.inspect.custom] = (depth) => {
Aug 25, 2016
Aug 25, 2016
657
return { bar: 'baz' };
658
};
659
660
util.inspect(obj);
Nov 16, 2016
Nov 16, 2016
661
// Returns: "{ bar: 'baz' }"
Aug 25, 2016
Aug 25, 2016
662
```
663
Feb 20, 2017
Feb 20, 2017
664
### util.inspect.custom
665
<!-- YAML
666
added: v6.6.0
Sep 15, 2018
Sep 15, 2018
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.
Feb 20, 2017
Feb 20, 2017
671
-->
672
Sep 15, 2018
Sep 15, 2018
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.
Feb 20, 2017
Feb 20, 2017
702
Aug 9, 2016
Aug 9, 2016
703
### util.inspect.defaultOptions
Aug 23, 2016
Aug 23, 2016
704
<!-- YAML
705
added: v6.4.0
706
-->
Aug 9, 2016
Aug 9, 2016
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');
Jun 1, 2017
Jun 1, 2017
716
const arr = Array(101).fill(0);
Aug 9, 2016
Aug 9, 2016
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
Oct 26, 2017
Oct 26, 2017
723
## util.isDeepStrictEqual(val1, val2)
724
<!-- YAML
Oct 31, 2017
Oct 31, 2017
725
added: v9.0.0
Oct 26, 2017
Oct 26, 2017
726
-->
727
728
* `val1` {any}
729
* `val2` {any}
Oct 31, 2017
Oct 31, 2017
730
* Returns: {boolean}
Oct 26, 2017
Oct 26, 2017
731
Feb 16, 2018
Feb 16, 2018
732
Returns `true` if there is deep strict equality between `val1` and `val2`.
Oct 26, 2017
Oct 26, 2017
733
Otherwise, returns `false`.
734
735
See [`assert.deepStrictEqual()`][] for more information about deep strict
736
equality.
737
May 9, 2017
May 9, 2017
738
## util.promisify(original)
739
<!-- YAML
May 30, 2017
May 30, 2017
740
added: v8.0.0
May 9, 2017
May 9, 2017
741
-->
742
743
* `original` {Function}
Oct 19, 2017
Oct 19, 2017
744
* Returns: {Function}
May 9, 2017
May 9, 2017
745
Dec 17, 2017
Dec 17, 2017
746
Takes a function following the common error-first callback style, i.e. taking
May 2, 2018
May 2, 2018
747
an `(err, value) => ...` callback as the last argument, and returns a version
May 9, 2017
May 9, 2017
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
Dec 12, 2017
Dec 12, 2017
780
final argument in all cases. If `original` is not a function, `promisify()`
Dec 17, 2017
Dec 17, 2017
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.
May 9, 2017
May 9, 2017
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
Nov 26, 2017
Nov 26, 2017
797
doSomething[util.promisify.custom] = (foo) => {
May 9, 2017
May 9, 2017
798
return getPromiseSomehow();
799
};
800
801
const promisified = util.promisify(doSomething);
802
console.log(promisified === doSomething[util.promisify.custom]);
Jun 29, 2017
Jun 29, 2017
803
// prints 'true'
May 9, 2017
May 9, 2017
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
Feb 23, 2018
Feb 23, 2018
809
For example, with a function that takes in
810
`(foo, onSuccessCallback, onErrorCallback)`:
Oct 13, 2017
Oct 13, 2017
811
812
```js
Nov 26, 2017
Nov 26, 2017
813
doSomething[util.promisify.custom] = (foo) => {
814
return new Promise((resolve, reject) => {
Oct 13, 2017
Oct 13, 2017
815
doSomething(foo, resolve, reject);
816
});
817
};
818
```
Dec 12, 2017
Dec 12, 2017
819
If `promisify.custom` is defined but is not a function, `promisify()` will
820
throw an error.
Oct 13, 2017
Oct 13, 2017
821
May 9, 2017
May 9, 2017
822
### util.promisify.custom
823
<!-- YAML
May 30, 2017
May 30, 2017
824
added: v8.0.0
May 9, 2017
May 9, 2017
825
-->
826
May 2, 2018
May 2, 2018
827
* {symbol} that can be used to declare custom promisified variants of functions,
May 9, 2017
May 9, 2017
828
see [Custom promisified functions][].
829
Aug 5, 2017
Aug 5, 2017
830
## Class: util.TextDecoder
Jul 24, 2017
Jul 24, 2017
831
<!-- YAML
Aug 10, 2017
Aug 10, 2017
832
added: v8.3.0
Jul 24, 2017
Jul 24, 2017
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
Aug 5, 2017
Aug 5, 2017
847
### WHATWG Supported Encodings
Jul 24, 2017
Jul 24, 2017
848
849
Per the [WHATWG Encoding Standard][], the encodings supported by the
850
`TextDecoder` API are outlined in the tables below. For each encoding,
Aug 5, 2017
Aug 5, 2017
851
one or more aliases may be used.
Jul 24, 2017
Jul 24, 2017
852
Aug 5, 2017
Aug 5, 2017
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
Jul 24, 2017
Jul 24, 2017
859
Aug 13, 2017
Aug 13, 2017
860
| Encoding | Aliases |
861
| ----------- | --------------------------------- |
862
| `'utf-8'` | `'unicode-1-1-utf-8'`, `'utf8'` |
863
| `'utf-16le'` | `'utf-16'` |
Jul 24, 2017
Jul 24, 2017
864
Aug 5, 2017
Aug 5, 2017
865
#### Encodings Supported by Default (With ICU)
866
Aug 13, 2017
Aug 13, 2017
867
| Encoding | Aliases |
868
| ----------- | --------------------------------- |
869
| `'utf-8'` | `'unicode-1-1-utf-8'`, `'utf8'` |
870
| `'utf-16le'` | `'utf-16'` |
871
| `'utf-16be'` | |
Aug 5, 2017
Aug 5, 2017
872
873
#### Encodings Requiring Full ICU Data
Jul 24, 2017
Jul 24, 2017
874
Aug 13, 2017
Aug 13, 2017
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'` |
Jul 24, 2017
Jul 24, 2017
911
Feb 8, 2018
Feb 8, 2018
912
The `'iso-8859-16'` encoding listed in the [WHATWG Encoding Standard][]
Jul 24, 2017
Jul 24, 2017
913
is not supported.
914
Aug 5, 2017
Aug 5, 2017
915
### new TextDecoder([encoding[, options]])
Sep 17, 2018
Sep 17, 2018
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
-->
Jul 24, 2017
Jul 24, 2017
923
924
* `encoding` {string} Identifies the `encoding` that this `TextDecoder` instance
Apr 4, 2018
Apr 4, 2018
925
supports. **Default:** `'utf-8'`.
Jul 24, 2017
Jul 24, 2017
926
* `options` {Object}
Apr 4, 2018
Apr 4, 2018
927
* `fatal` {boolean} `true` if decoding failures are fatal. This option is only
928
supported when ICU is enabled (see [Internationalization][]). **Default:**
929
`false`.
Jul 24, 2017
Jul 24, 2017
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
Apr 4, 2018
Apr 4, 2018
933
`'utf-8'`, `'utf-16be'` or `'utf-16le'`. **Default:** `false`.
Jul 24, 2017
Jul 24, 2017
934
935
Creates an new `TextDecoder` instance. The `encoding` may specify one of the
936
supported encodings or an alias.
937
Sep 17, 2018
Sep 17, 2018
938
The `TextDecoder` class is also available on the global object.
939
Aug 5, 2017
Aug 5, 2017
940
### textDecoder.decode([input[, options]])
Jul 24, 2017
Jul 24, 2017
941
942
* `input` {ArrayBuffer|DataView|TypedArray} An `ArrayBuffer`, `DataView` or
May 2, 2018
May 2, 2018
943
`TypedArray` instance containing the encoded data.
Jul 24, 2017
Jul 24, 2017
944
* `options` {Object}
945
* `stream` {boolean} `true` if additional chunks of data are expected.
Apr 4, 2018
Apr 4, 2018
946
**Default:** `false`.
Jul 24, 2017
Jul 24, 2017
947
* Returns: {string}
948
949
Decodes the `input` and returns a string. If `options.stream` is `true`, any
Nov 28, 2017
Nov 28, 2017
950
incomplete byte sequences occurring at the end of the `input` are buffered
Jul 24, 2017
Jul 24, 2017
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
Aug 5, 2017
Aug 5, 2017
956
### textDecoder.encoding
Jul 24, 2017
Jul 24, 2017
957
Aug 5, 2017
Aug 5, 2017
958
* {string}
Jul 24, 2017
Jul 24, 2017
959
960
The encoding supported by the `TextDecoder` instance.
961
Aug 5, 2017
Aug 5, 2017
962
### textDecoder.fatal
Jul 24, 2017
Jul 24, 2017
963
Aug 5, 2017
Aug 5, 2017
964
* {boolean}
Jul 24, 2017
Jul 24, 2017
965
966
The value will be `true` if decoding errors result in a `TypeError` being
967
thrown.
968
Aug 5, 2017
Aug 5, 2017
969
### textDecoder.ignoreBOM
Jul 24, 2017
Jul 24, 2017
970
Aug 5, 2017
Aug 5, 2017
971
* {boolean}
Jul 24, 2017
Jul 24, 2017
972
973
The value will be `true` if the decoding result will include the byte order
974
mark.
975
Aug 5, 2017
Aug 5, 2017
976
## Class: util.TextEncoder
Jul 24, 2017
Jul 24, 2017
977
<!-- YAML
Aug 10, 2017
Aug 10, 2017
978
added: v8.3.0
Sep 17, 2018
Sep 17, 2018
979
changes:
980
- version: REPLACEME
981
pr-url: REPLACEME
982
description: The class is now available on the global object.
Jul 24, 2017
Jul 24, 2017
983
-->
984
985
An implementation of the [WHATWG Encoding Standard][] `TextEncoder` API. All
Aug 5, 2017
Aug 5, 2017
986
instances of `TextEncoder` only support UTF-8 encoding.
Jul 24, 2017
Jul 24, 2017
987
988
```js
989
const encoder = new TextEncoder();
990
const uint8array = encoder.encode('this is some data');
991
```
992
Sep 17, 2018
Sep 17, 2018
993
The `TextEncoder` class is also available on the global object.
994
Aug 5, 2017
Aug 5, 2017
995
### textEncoder.encode([input])
Jul 24, 2017
Jul 24, 2017
996
Apr 4, 2018
Apr 4, 2018
997
* `input` {string} The text to encode. **Default:** an empty string.
Jul 24, 2017
Jul 24, 2017
998
* Returns: {Uint8Array}
999
Aug 5, 2017
Aug 5, 2017
1000
UTF-8 encodes the `input` string and returns a `Uint8Array` containing the