5 These functions are in the module `'util'`. Use `require('util')` to
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.
15 ## util.debuglog(section)
17 * `section` {String} The section of the program to be debugged
18 * Returns: {Function} The logging function
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.
29 var debuglog = util.debuglog('foo');
32 debuglog('hello from foo [%d]', bar);
35 If this program is run with `NODE_DEBUG=foo` in the environment, then
36 it will output something like:
38 FOO 3245: hello from foo [123]
40 where `3245` is the process id. If it is not run with that
41 environment variable set, then it will not print anything.
43 You may separate multiple `NODE_DEBUG` environment variables with a
44 comma. For example, `NODE_DEBUG=fs,net,tls`.
46 ## util.format(format[, ...])
48 Returns a formatted string using the first argument as a `printf`-like format.
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:
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.
60 If the placeholder does not have a corresponding argument, the placeholder is
63 util.format('%s:%s', 'foo'); // 'foo:%s'
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.
69 util.format('%s:%s', 'foo', 'bar', 'baz'); // 'foo:bar baz'
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()`.
75 util.format(1, 2, 3); // '1 2 3'
80 Output with timestamp on `stdout`.
82 require('util').log('Timestamped message.');
84 ## util.inspect(object[, options])
86 Return a string representation of `object`, which is useful for debugging.
88 An optional *options* object may be passed that alters certain aspects of the
91 - `showHidden` - if `true` then the object's non-enumerable and symbol
92 properties will be shown too. Defaults to `false`.
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`.
98 - `colors` - if `true`, then the output will be styled with ANSI color codes.
99 Defaults to `false`. Colors are customizable, see below.
101 - `customInspect` - if `false`, then custom `inspect(depth, opts)` functions
102 defined on the objects being inspected won't be called. Defaults to `true`.
104 Example of inspecting all properties of the `util` object:
106 var util = require('util');
108 console.log(util.inspect(util, { showHidden: true, depth: null }));
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()`.
114 ### Customizing `util.inspect` colors
118 Color output (if enabled) of `util.inspect` is customizable globally
119 via `util.inspect.styles` and `util.inspect.colors` objects.
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:
131 * `special` - only function at this time (cyan)
132 * `name` (intentionally no styling)
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.
138 ### Custom `inspect()` function on Objects
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:
145 var util = require('util');
147 var obj = { name: 'nate' };
148 obj.inspect = function(depth) {
149 return '{' + this.name + '}';
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:
159 var obj = { foo: 'this will not show up in the inspect() output' };
160 obj.inspect = function(depth) {
161 return { bar: 'baz' };
168 ## util.isArray(object)
170 Internal alias for Array.isArray.
172 Returns `true` if the given "object" is an `Array`. `false` otherwise.
174 var util = require('util');
178 util.isArray(new Array)
184 ## util.isRegExp(object)
186 Returns `true` if the given "object" is a `RegExp`. `false` otherwise.
188 var util = require('util');
190 util.isRegExp(/some regexp/)
192 util.isRegExp(new RegExp('another regexp'))
198 ## util.isDate(object)
200 Returns `true` if the given "object" is a `Date`. `false` otherwise.
202 var util = require('util');
204 util.isDate(new Date())
207 // false (without 'new' returns a String)
212 ## util.isError(object)
214 Returns `true` if the given "object" is an `Error`. `false` otherwise.
216 var util = require('util');
218 util.isError(new Error())
220 util.isError(new TypeError())
222 util.isError({ name: 'Error', message: 'an error occurred' })
226 ## util.isBoolean(object)
228 Returns `true` if the given "object" is a `Boolean`. `false` otherwise.
230 var util = require('util');
236 util.isBoolean(false)
240 ## util.isNull(object)
242 Returns `true` if the given "object" is strictly `null`. `false` otherwise.
244 var util = require('util');
248 util.isNull(undefined)
254 ## util.isNullOrUndefined(object)
256 Returns `true` if the given "object" is `null` or `undefined`. `false` otherwise.
258 var util = require('util');
260 util.isNullOrUndefined(0)
262 util.isNullOrUndefined(undefined)
264 util.isNullOrUndefined(null)
268 ## util.isNumber(object)
270 Returns `true` if the given "object" is a `Number`. `false` otherwise.
272 var util = require('util');
276 util.isNumber(Infinity)
284 ## util.isString(object)
286 Returns `true` if the given "object" is a `String`. `false` otherwise.
288 var util = require('util');
294 util.isString(String('foo'))
300 ## util.isSymbol(object)
302 Returns `true` if the given "object" is a `Symbol`. `false` otherwise.
304 var util = require('util');
310 util.isSymbol(Symbol('foo'))
314 ## util.isUndefined(object)
316 Returns `true` if the given "object" is `undefined`. `false` otherwise.
318 var util = require('util');
323 util.isUndefined(foo)
325 util.isUndefined(null)
329 ## util.isObject(object)
331 Returns `true` if the given "object" is strictly an `Object` __and__ not a
332 `Function`. `false` otherwise.
334 var util = require('util');
342 util.isObject(function(){})
346 ## util.isFunction(object)
348 Returns `true` if the given "object" is a `Function`. `false` otherwise.
350 var util = require('util');
353 var Bar = function() {};
363 ## util.isPrimitive(object)
365 Returns `true` if the given "object" is a primitive type. `false` otherwise.
367 var util = require('util');
371 util.isPrimitive('foo')
373 util.isPrimitive(false)
375 util.isPrimitive(null)
377 util.isPrimitive(undefined)
381 util.isPrimitive(function() {})
383 util.isPrimitive(/^$/)
385 util.isPrimitive(new Date())
389 ## util.isBuffer(object)
391 Returns `true` if the given "object" is a `Buffer`. `false` otherwise.
393 var util = require('util');
395 util.isBuffer({ length: 0 })
399 util.isBuffer(new Buffer('hello world'))
403 ## util.inherits(constructor, superConstructor)
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`.
410 As an additional convenience, `superConstructor` will be accessible
411 through the `constructor.super_` property.
413 var util = require("util");
414 var events = require("events");
416 function MyStream() {
417 events.EventEmitter.call(this);
420 util.inherits(MyStream, events.EventEmitter);
422 MyStream.prototype.write = function(data) {
423 this.emit("data", data);
426 var stream = new MyStream();
428 console.log(stream instanceof events.EventEmitter); // true
429 console.log(MyStream.super_ === events.EventEmitter); // true
431 stream.on("data", function(data) {
432 console.log('Received data: "' + data + '"');
434 stream.write("It works!"); // Received data: "It works!"
437 ## util.deprecate(function, string)
439 Marks that a method should not be used any more.
441 var util = require('util');
443 exports.puts = util.deprecate(function() {
444 for (var i = 0, len = arguments.length; i < len; ++i) {
445 process.stdout.write(arguments[i] + '\n');
447 }, 'util.puts: Use console.log instead');
449 It returns a modified function which warns once by default.
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.)
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.
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.
463 `process.throwDeprecation` takes precedence over `process.traceDeprecation`.
465 ## util.debug(string)
467 Stability: 0 - Deprecated: use console.error() instead.
469 Deprecated predecessor of `console.error`.
473 Stability: 0 - Deprecated: Use console.error() instead.
475 Deprecated predecessor of `console.error`.
479 Stability: 0 - Deprecated: Use console.log() instead.
481 Deprecated predecessor of `console.log`.
485 Stability: 0 - Deprecated: Use `console.log` instead.
487 Deprecated predecessor of `console.log`.
490 ## util.pump(readableStream, writableStream[, callback])
492 Stability: 0 - Deprecated: Use readableStream.pipe(writableStream)
494 Deprecated predecessor of `stream.pipe()`.