9633e0e388dd8e5e5c1e8b4d7a57459d5f61b58b
[platform/upstream/nodejs.git] / doc / api / util.markdown
1 # util
2
3     Stability: 2 - Stable
4
5 These functions are in the module `'util'`. Use `require('util')` to
6 access them.
7
8 The `util` module is primarily designed to support the needs of Node.js's
9 internal APIs.  Many of these utilities are useful for your own
10 programs.  If you find that these functions are lacking for your
11 purposes, however, you are encouraged to write your own utilities.  We
12 are not interested in any future additions to the `util` module that
13 are unnecessary for Node.js's internal functionality.
14
15 ## util.debug(string)
16
17     Stability: 0 - Deprecated: use console.error() instead.
18
19 Deprecated predecessor of `console.error`.
20
21 ## util.debuglog(section)
22
23 * `section` {String} The section of the program to be debugged
24 * Returns: {Function} The logging function
25
26 This is used to create a function which conditionally writes to stderr
27 based on the existence of a `NODE_DEBUG` environment variable.  If the
28 `section` name appears in that environment variable, then the returned
29 function will be similar to `console.error()`.  If not, then the
30 returned function is a no-op.
31
32 For example:
33
34 ```js
35 var debuglog = util.debuglog('foo');
36
37 var bar = 123;
38 debuglog('hello from foo [%d]', bar);
39 ```
40
41 If this program is run with `NODE_DEBUG=foo` in the environment, then
42 it will output something like:
43
44 ```
45 FOO 3245: hello from foo [123]
46 ```
47
48 where `3245` is the process id.  If it is not run with that
49 environment variable set, then it will not print anything.
50
51 You may separate multiple `NODE_DEBUG` environment variables with a
52 comma.  For example, `NODE_DEBUG=fs,net,tls`.
53
54 ## util.deprecate(function, string)
55
56 Marks that a method should not be used any more.
57
58 ```js
59 const util = require('util');
60
61 exports.puts = util.deprecate(function() {
62   for (var i = 0, len = arguments.length; i < len; ++i) {
63     process.stdout.write(arguments[i] + '\n');
64   }
65 }, 'util.puts: Use console.log instead');
66 ```
67
68 It returns a modified function which warns once by default.
69
70 If `--no-deprecation` is set then this function is a NO-OP.  Configurable
71 at run-time through the `process.noDeprecation` boolean (only effective
72 when set before a module is loaded.)
73
74 If `--trace-deprecation` is set, a warning and a stack trace are logged
75 to the console the first time the deprecated API is used.  Configurable
76 at run-time through the `process.traceDeprecation` boolean.
77
78 If `--throw-deprecation` is set then the application throws an exception
79 when the deprecated API is used.  Configurable at run-time through the
80 `process.throwDeprecation` boolean.
81
82 `process.throwDeprecation` takes precedence over `process.traceDeprecation`.
83
84 ## util.error([...])
85
86     Stability: 0 - Deprecated: Use console.error() instead.
87
88 Deprecated predecessor of `console.error`.
89
90 ## util.format(format[, ...])
91
92 Returns a formatted string using the first argument as a `printf`-like format.
93
94 The first argument is a string that contains zero or more *placeholders*.
95 Each placeholder is replaced with the converted value from its corresponding
96 argument. Supported placeholders are:
97
98 * `%s` - String.
99 * `%d` - Number (both integer and float).
100 * `%j` - JSON.  Replaced with the string `'[Circular]'` if the argument
101 contains circular references.
102 * `%%` - single percent sign (`'%'`). This does not consume an argument.
103
104 If the placeholder does not have a corresponding argument, the placeholder is
105 not replaced.
106
107 ```js
108 util.format('%s:%s', 'foo'); // 'foo:%s'
109 ```
110
111 If there are more arguments than placeholders, the extra arguments are
112 coerced to strings (for objects and symbols, `util.inspect()` is used)
113 and then concatenated, delimited by a space.
114
115 ```js
116 util.format('%s:%s', 'foo', 'bar', 'baz'); // 'foo:bar baz'
117 ```
118
119 If the first argument is not a format string then `util.format()` returns
120 a string that is the concatenation of all its arguments separated by spaces.
121 Each argument is converted to a string with `util.inspect()`.
122
123 ```js
124 util.format(1, 2, 3); // '1 2 3'
125 ```
126
127 ## util.inherits(constructor, superConstructor)
128
129 Inherit the prototype methods from one [constructor][] into another.  The
130 prototype of `constructor` will be set to a new object created from
131 `superConstructor`.
132
133 As an additional convenience, `superConstructor` will be accessible
134 through the `constructor.super_` property.
135
136 ```js
137 const util = require('util');
138 const EventEmitter = require('events');
139
140 function MyStream() {
141     EventEmitter.call(this);
142 }
143
144 util.inherits(MyStream, EventEmitter);
145
146 MyStream.prototype.write = function(data) {
147     this.emit('data', data);
148 }
149
150 var stream = new MyStream();
151
152 console.log(stream instanceof EventEmitter); // true
153 console.log(MyStream.super_ === EventEmitter); // true
154
155 stream.on('data', (data) => {
156   console.log(`Received data: "${data}"`);
157 })
158 stream.write('It works!'); // Received data: "It works!"
159 ```
160
161 ## util.inspect(object[, options])
162
163 Return a string representation of `object`, which is useful for debugging.
164
165 An optional *options* object may be passed that alters certain aspects of the
166 formatted string:
167
168  - `showHidden` - if `true` then the object's non-enumerable and symbol
169    properties will be shown too. Defaults to `false`.
170
171  - `depth` - tells `inspect` how many times to recurse while formatting the
172    object. This is useful for inspecting large complicated objects. Defaults to
173    `2`. To make it recurse indefinitely pass `null`.
174
175  - `colors` - if `true`, then the output will be styled with ANSI color codes.
176    Defaults to `false`. Colors are customizable, see [Customizing
177    `util.inspect` colors][].
178
179  - `customInspect` - if `false`, then custom `inspect(depth, opts)` functions
180    defined on the objects being inspected won't be called. Defaults to `true`.
181
182 Example of inspecting all properties of the `util` object:
183
184 ```js
185 const util = require('util');
186
187 console.log(util.inspect(util, { showHidden: true, depth: null }));
188 ```
189
190 Values may supply their own custom `inspect(depth, opts)` functions, when
191 called they receive the current depth in the recursive inspection, as well as
192 the options object passed to `util.inspect()`.
193
194 ### Customizing `util.inspect` colors
195
196 <!-- type=misc -->
197
198 Color output (if enabled) of `util.inspect` is customizable globally
199 via `util.inspect.styles` and `util.inspect.colors` objects.
200
201 `util.inspect.styles` is a map assigning each style a color
202 from `util.inspect.colors`.
203 Highlighted styles and their default values are:
204  * `number` (yellow)
205  * `boolean` (yellow)
206  * `string` (green)
207  * `date` (magenta)
208  * `regexp` (red)
209  * `null` (bold)
210  * `undefined` (grey)
211  * `special` - only function at this time (cyan)
212  * `name` (intentionally no styling)
213
214 Predefined color codes are: `white`, `grey`, `black`, `blue`, `cyan`,
215 `green`, `magenta`, `red` and `yellow`.
216 There are also `bold`, `italic`, `underline` and `inverse` codes.
217
218 ### Custom `inspect()` function on Objects
219
220 <!-- type=misc -->
221
222 Objects also may define their own `inspect(depth)` function which `util.inspect()`
223 will invoke and use the result of when inspecting the object:
224
225 ```js
226 const util = require('util');
227
228 var obj = { name: 'nate' };
229 obj.inspect = function(depth) {
230   return `{${this.name}}`;
231 };
232
233 util.inspect(obj);
234   // "{nate}"
235 ```
236
237 You may also return another Object entirely, and the returned String will be
238 formatted according to the returned Object. This is similar to how
239 `JSON.stringify()` works:
240
241 ```js
242 var obj = { foo: 'this will not show up in the inspect() output' };
243 obj.inspect = function(depth) {
244   return { bar: 'baz' };
245 };
246
247 util.inspect(obj);
248   // "{ bar: 'baz' }"
249 ```
250
251 ## util.isArray(object)
252
253     Stability: 0 - Deprecated
254
255 Internal alias for [`Array.isArray`][].
256
257 Returns `true` if the given "object" is an `Array`. `false` otherwise.
258
259 ```js
260 const util = require('util');
261
262 util.isArray([])
263   // true
264 util.isArray(new Array)
265   // true
266 util.isArray({})
267   // false
268 ```
269
270 ## util.isBoolean(object)
271
272     Stability: 0 - Deprecated
273
274 Returns `true` if the given "object" is a `Boolean`. `false` otherwise.
275
276 ```js
277 const util = require('util');
278
279 util.isBoolean(1)
280   // false
281 util.isBoolean(0)
282   // false
283 util.isBoolean(false)
284   // true
285 ```
286
287 ## util.isBuffer(object)
288
289     Stability: 0 - Deprecated
290
291 Use `Buffer.isBuffer()` instead.
292
293 Returns `true` if the given "object" is a `Buffer`. `false` otherwise.
294
295 ```js
296 const util = require('util');
297
298 util.isBuffer({ length: 0 })
299   // false
300 util.isBuffer([])
301   // false
302 util.isBuffer(new Buffer('hello world'))
303   // true
304 ```
305
306 ## util.isDate(object)
307
308     Stability: 0 - Deprecated
309
310 Returns `true` if the given "object" is a `Date`. `false` otherwise.
311
312 ```js
313 const util = require('util');
314
315 util.isDate(new Date())
316   // true
317 util.isDate(Date())
318   // false (without 'new' returns a String)
319 util.isDate({})
320   // false
321 ```
322
323 ## util.isError(object)
324
325     Stability: 0 - Deprecated
326
327 Returns `true` if the given "object" is an [`Error`][]. `false` otherwise.
328
329 ```js
330 const util = require('util');
331
332 util.isError(new Error())
333   // true
334 util.isError(new TypeError())
335   // true
336 util.isError({ name: 'Error', message: 'an error occurred' })
337   // false
338 ```
339
340 ## util.isFunction(object)
341
342     Stability: 0 - Deprecated
343
344 Returns `true` if the given "object" is a `Function`. `false` otherwise.
345
346 ```js
347 const util = require('util');
348
349 function Foo() {}
350 var Bar = function() {};
351
352 util.isFunction({})
353   // false
354 util.isFunction(Foo)
355   // true
356 util.isFunction(Bar)
357   // true
358 ```
359
360 ## util.isNull(object)
361
362     Stability: 0 - Deprecated
363
364 Returns `true` if the given "object" is strictly `null`. `false` otherwise.
365
366 ```js
367 const util = require('util');
368
369 util.isNull(0)
370   // false
371 util.isNull(undefined)
372   // false
373 util.isNull(null)
374   // true
375 ```
376
377 ## util.isNullOrUndefined(object)
378
379     Stability: 0 - Deprecated
380
381 Returns `true` if the given "object" is `null` or `undefined`. `false` otherwise.
382
383 ```js
384 const util = require('util');
385
386 util.isNullOrUndefined(0)
387   // false
388 util.isNullOrUndefined(undefined)
389   // true
390 util.isNullOrUndefined(null)
391   // true
392 ```
393
394 ## util.isNumber(object)
395
396     Stability: 0 - Deprecated
397
398 Returns `true` if the given "object" is a `Number`. `false` otherwise.
399
400 ```js
401 const util = require('util');
402
403 util.isNumber(false)
404   // false
405 util.isNumber(Infinity)
406   // true
407 util.isNumber(0)
408   // true
409 util.isNumber(NaN)
410   // true
411 ```
412
413 ## util.isObject(object)
414
415     Stability: 0 - Deprecated
416
417 Returns `true` if the given "object" is strictly an `Object` __and__ not a
418 `Function`. `false` otherwise.
419
420 ```js
421 const util = require('util');
422
423 util.isObject(5)
424   // false
425 util.isObject(null)
426   // false
427 util.isObject({})
428   // true
429 util.isObject(function(){})
430   // false
431 ```
432
433 ## util.isPrimitive(object)
434
435     Stability: 0 - Deprecated
436
437 Returns `true` if the given "object" is a primitive type. `false` otherwise.
438
439 ```js
440 const util = require('util');
441
442 util.isPrimitive(5)
443   // true
444 util.isPrimitive('foo')
445   // true
446 util.isPrimitive(false)
447   // true
448 util.isPrimitive(null)
449   // true
450 util.isPrimitive(undefined)
451   // true
452 util.isPrimitive({})
453   // false
454 util.isPrimitive(function() {})
455   // false
456 util.isPrimitive(/^$/)
457   // false
458 util.isPrimitive(new Date())
459   // false
460 ```
461
462 ## util.isRegExp(object)
463
464     Stability: 0 - Deprecated
465
466 Returns `true` if the given "object" is a `RegExp`. `false` otherwise.
467
468 ```js
469 const util = require('util');
470
471 util.isRegExp(/some regexp/)
472   // true
473 util.isRegExp(new RegExp('another regexp'))
474   // true
475 util.isRegExp({})
476   // false
477 ```
478
479 ## util.isString(object)
480
481     Stability: 0 - Deprecated
482
483 Returns `true` if the given "object" is a `String`. `false` otherwise.
484
485 ```js
486 const util = require('util');
487
488 util.isString('')
489   // true
490 util.isString('foo')
491   // true
492 util.isString(String('foo'))
493   // true
494 util.isString(5)
495   // false
496 ```
497
498 ## util.isSymbol(object)
499
500     Stability: 0 - Deprecated
501
502 Returns `true` if the given "object" is a `Symbol`. `false` otherwise.
503
504 ```js
505 const util = require('util');
506
507 util.isSymbol(5)
508   // false
509 util.isSymbol('foo')
510   // false
511 util.isSymbol(Symbol('foo'))
512   // true
513 ```
514
515 ## util.isUndefined(object)
516
517     Stability: 0 - Deprecated
518
519 Returns `true` if the given "object" is `undefined`. `false` otherwise.
520
521 ```js
522 const util = require('util');
523
524 var foo;
525 util.isUndefined(5)
526   // false
527 util.isUndefined(foo)
528   // true
529 util.isUndefined(null)
530   // false
531 ```
532
533 ## util.log(string)
534
535 Output with timestamp on `stdout`.
536
537     require('util').log('Timestamped message.');
538
539 ## util.print([...])
540
541     Stability: 0 - Deprecated: Use `console.log` instead.
542
543 Deprecated predecessor of `console.log`.
544
545 ## util.pump(readableStream, writableStream[, callback])
546
547     Stability: 0 - Deprecated: Use readableStream.pipe(writableStream)
548
549 Deprecated predecessor of `stream.pipe()`.
550
551 ## util.puts([...])
552
553     Stability: 0 - Deprecated: Use console.log() instead.
554
555 Deprecated predecessor of `console.log`.
556
557 [`Array.isArray`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
558 [constructor]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/constructor
559 [Customizing `util.inspect` colors]: #util_customizing_util_inspect_colors
560 [here]: #util_customizing_util_inspect_colors
561 [`Error`]: errors.html#errors_class_error