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