4574ae452b231b17ae299fbf8c6af41b2971dd0a
[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 below.
165
166  - `customInspect` - if `false`, then custom `inspect(depth, opts)` functions
167    defined on the objects being inspected won't be called. Defaults to `true`.
168
169 Example of inspecting all properties of the `util` object:
170
171     const util = require('util');
172
173     console.log(util.inspect(util, { showHidden: true, depth: null }));
174
175 Values may supply their own custom `inspect(depth, opts)` functions, when
176 called they receive the current depth in the recursive inspection, as well as
177 the options object passed to `util.inspect()`.
178
179 ### Customizing `util.inspect` colors
180
181 <!-- type=misc -->
182
183 Color output (if enabled) of `util.inspect` is customizable globally
184 via `util.inspect.styles` and `util.inspect.colors` objects.
185
186 `util.inspect.styles` is a map assigning each style a color
187 from `util.inspect.colors`.
188 Highlighted styles and their default values are:
189  * `number` (yellow)
190  * `boolean` (yellow)
191  * `string` (green)
192  * `date` (magenta)
193  * `regexp` (red)
194  * `null` (bold)
195  * `undefined` (grey)
196  * `special` - only function at this time (cyan)
197  * `name` (intentionally no styling)
198
199 Predefined color codes are: `white`, `grey`, `black`, `blue`, `cyan`,
200 `green`, `magenta`, `red` and `yellow`.
201 There are also `bold`, `italic`, `underline` and `inverse` codes.
202
203 ### Custom `inspect()` function on Objects
204
205 <!-- type=misc -->
206
207 Objects also may define their own `inspect(depth)` function which `util.inspect()`
208 will invoke and use the result of when inspecting the object:
209
210     const util = require('util');
211
212     var obj = { name: 'nate' };
213     obj.inspect = function(depth) {
214       return `{${this.name}}`;
215     };
216
217     util.inspect(obj);
218       // "{nate}"
219
220 You may also return another Object entirely, and the returned String will be
221 formatted according to the returned Object. This is similar to how
222 `JSON.stringify()` works:
223
224     var obj = { foo: 'this will not show up in the inspect() output' };
225     obj.inspect = function(depth) {
226       return { bar: 'baz' };
227     };
228
229     util.inspect(obj);
230       // "{ bar: 'baz' }"
231
232 ## util.isArray(object)
233
234     Stability: 0 - Deprecated
235
236 Internal alias for [`Array.isArray`][].
237
238 Returns `true` if the given "object" is an `Array`. `false` otherwise.
239
240     const util = require('util');
241
242     util.isArray([])
243       // true
244     util.isArray(new Array)
245       // true
246     util.isArray({})
247       // false
248
249 ## util.isBoolean(object)
250
251     Stability: 0 - Deprecated
252
253 Returns `true` if the given "object" is a `Boolean`. `false` otherwise.
254
255     const util = require('util');
256
257     util.isBoolean(1)
258       // false
259     util.isBoolean(0)
260       // false
261     util.isBoolean(false)
262       // true
263
264 ## util.isBuffer(object)
265
266     Stability: 0 - Deprecated
267
268 Use `Buffer.isBuffer()` instead.
269
270 Returns `true` if the given "object" is a `Buffer`. `false` otherwise.
271
272     const util = require('util');
273
274     util.isBuffer({ length: 0 })
275       // false
276     util.isBuffer([])
277       // false
278     util.isBuffer(new Buffer('hello world'))
279       // true
280
281 ## util.isDate(object)
282
283     Stability: 0 - Deprecated
284
285 Returns `true` if the given "object" is a `Date`. `false` otherwise.
286
287     const util = require('util');
288
289     util.isDate(new Date())
290       // true
291     util.isDate(Date())
292       // false (without 'new' returns a String)
293     util.isDate({})
294       // false
295
296 ## util.isError(object)
297
298     Stability: 0 - Deprecated
299
300 Returns `true` if the given "object" is an [`Error`][]. `false` otherwise.
301
302     const util = require('util');
303
304     util.isError(new Error())
305       // true
306     util.isError(new TypeError())
307       // true
308     util.isError({ name: 'Error', message: 'an error occurred' })
309       // false
310
311 ## util.isFunction(object)
312
313     Stability: 0 - Deprecated
314
315 Returns `true` if the given "object" is a `Function`. `false` otherwise.
316
317     const util = require('util');
318
319     function Foo() {}
320     var Bar = function() {};
321
322     util.isFunction({})
323       // false
324     util.isFunction(Foo)
325       // true
326     util.isFunction(Bar)
327       // true
328
329 ## util.isNull(object)
330
331     Stability: 0 - Deprecated
332
333 Returns `true` if the given "object" is strictly `null`. `false` otherwise.
334
335     const util = require('util');
336
337     util.isNull(0)
338       // false
339     util.isNull(undefined)
340       // false
341     util.isNull(null)
342       // true
343
344 ## util.isNullOrUndefined(object)
345
346     Stability: 0 - Deprecated
347
348 Returns `true` if the given "object" is `null` or `undefined`. `false` otherwise.
349
350     const util = require('util');
351
352     util.isNullOrUndefined(0)
353       // false
354     util.isNullOrUndefined(undefined)
355       // true
356     util.isNullOrUndefined(null)
357       // true
358
359 ## util.isNumber(object)
360
361     Stability: 0 - Deprecated
362
363 Returns `true` if the given "object" is a `Number`. `false` otherwise.
364
365     const util = require('util');
366
367     util.isNumber(false)
368       // false
369     util.isNumber(Infinity)
370       // true
371     util.isNumber(0)
372       // true
373     util.isNumber(NaN)
374       // true
375
376 ## util.isObject(object)
377
378     Stability: 0 - Deprecated
379
380 Returns `true` if the given "object" is strictly an `Object` __and__ not a
381 `Function`. `false` otherwise.
382
383     const util = require('util');
384
385     util.isObject(5)
386       // false
387     util.isObject(null)
388       // false
389     util.isObject({})
390       // true
391     util.isObject(function(){})
392       // false
393
394 ## util.isPrimitive(object)
395
396     Stability: 0 - Deprecated
397
398 Returns `true` if the given "object" is a primitive type. `false` otherwise.
399
400     const util = require('util');
401
402     util.isPrimitive(5)
403       // true
404     util.isPrimitive('foo')
405       // true
406     util.isPrimitive(false)
407       // true
408     util.isPrimitive(null)
409       // true
410     util.isPrimitive(undefined)
411       // true
412     util.isPrimitive({})
413       // false
414     util.isPrimitive(function() {})
415       // false
416     util.isPrimitive(/^$/)
417       // false
418     util.isPrimitive(new Date())
419       // false
420
421 ## util.isRegExp(object)
422
423     Stability: 0 - Deprecated
424
425 Returns `true` if the given "object" is a `RegExp`. `false` otherwise.
426
427     const util = require('util');
428
429     util.isRegExp(/some regexp/)
430       // true
431     util.isRegExp(new RegExp('another regexp'))
432       // true
433     util.isRegExp({})
434       // false
435
436 ## util.isString(object)
437
438     Stability: 0 - Deprecated
439
440 Returns `true` if the given "object" is a `String`. `false` otherwise.
441
442     const util = require('util');
443
444     util.isString('')
445       // true
446     util.isString('foo')
447       // true
448     util.isString(String('foo'))
449       // true
450     util.isString(5)
451       // false
452
453 ## util.isSymbol(object)
454
455     Stability: 0 - Deprecated
456
457 Returns `true` if the given "object" is a `Symbol`. `false` otherwise.
458
459     const util = require('util');
460
461     util.isSymbol(5)
462       // false
463     util.isSymbol('foo')
464       // false
465     util.isSymbol(Symbol('foo'))
466       // true
467
468 ## util.isUndefined(object)
469
470     Stability: 0 - Deprecated
471
472 Returns `true` if the given "object" is `undefined`. `false` otherwise.
473
474     const util = require('util');
475
476     var foo;
477     util.isUndefined(5)
478       // false
479     util.isUndefined(foo)
480       // true
481     util.isUndefined(null)
482       // false
483
484 ## util.log(string)
485
486 Output with timestamp on `stdout`.
487
488     require('util').log('Timestamped message.');
489
490 ## util.print([...])
491
492     Stability: 0 - Deprecated: Use `console.log` instead.
493
494 Deprecated predecessor of `console.log`.
495
496 ## util.pump(readableStream, writableStream[, callback])
497
498     Stability: 0 - Deprecated: Use readableStream.pipe(writableStream)
499
500 Deprecated predecessor of `stream.pipe()`.
501
502 ## util.puts([...])
503
504     Stability: 0 - Deprecated: Use console.log() instead.
505
506 Deprecated predecessor of `console.log`.
507
508 [`Array.isArray`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
509 [constructor]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/constructor
510 [`Error`]: errors.html#errors_class_error