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