5 These functions are in the module `'util'`. Use `require('util')` to
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.
17 Stability: 0 - Deprecated: use console.error() instead.
19 Deprecated predecessor of `console.error`.
21 ## util.debuglog(section)
23 * `section` {String} The section of the program to be debugged
24 * Returns: {Function} The logging function
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.
35 var debuglog = util.debuglog('foo');
38 debuglog('hello from foo [%d]', bar);
41 If this program is run with `NODE_DEBUG=foo` in the environment, then
42 it will output something like:
44 FOO 3245: hello from foo [123]
46 where `3245` is the process id. If it is not run with that
47 environment variable set, then it will not print anything.
49 You may separate multiple `NODE_DEBUG` environment variables with a
50 comma. For example, `NODE_DEBUG=fs,net,tls`.
52 ## util.deprecate(function, string)
54 Marks that a method should not be used any more.
56 const util = require('util');
58 exports.puts = util.deprecate(function() {
59 for (var i = 0, len = arguments.length; i < len; ++i) {
60 process.stdout.write(arguments[i] + '\n');
62 }, 'util.puts: Use console.log instead');
64 It returns a modified function which warns once by default.
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.)
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.
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.
78 `process.throwDeprecation` takes precedence over `process.traceDeprecation`.
82 Stability: 0 - Deprecated: Use console.error() instead.
84 Deprecated predecessor of `console.error`.
86 ## util.format(format[, ...])
88 Returns a formatted string using the first argument as a `printf`-like format.
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:
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.
100 If the placeholder does not have a corresponding argument, the placeholder is
103 util.format('%s:%s', 'foo'); // 'foo:%s'
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.
109 util.format('%s:%s', 'foo', 'bar', 'baz'); // 'foo:bar baz'
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()`.
115 util.format(1, 2, 3); // '1 2 3'
117 ## util.inherits(constructor, superConstructor)
119 Inherit the prototype methods from one [constructor][] into another. The
120 prototype of `constructor` will be set to a new object created from
123 As an additional convenience, `superConstructor` will be accessible
124 through the `constructor.super_` property.
126 const util = require('util');
127 const EventEmitter = require('events');
129 function MyStream() {
130 EventEmitter.call(this);
133 util.inherits(MyStream, EventEmitter);
135 MyStream.prototype.write = function(data) {
136 this.emit('data', data);
139 var stream = new MyStream();
141 console.log(stream instanceof EventEmitter); // true
142 console.log(MyStream.super_ === EventEmitter); // true
144 stream.on('data', (data) => {
145 console.log(`Received data: "${data}"`);
147 stream.write('It works!'); // Received data: "It works!"
149 ## util.inspect(object[, options])
151 Return a string representation of `object`, which is useful for debugging.
153 An optional *options* object may be passed that alters certain aspects of the
156 - `showHidden` - if `true` then the object's non-enumerable and symbol
157 properties will be shown too. Defaults to `false`.
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`.
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][].
167 - `customInspect` - if `false`, then custom `inspect(depth, opts)` functions
168 defined on the objects being inspected won't be called. Defaults to `true`.
170 Example of inspecting all properties of the `util` object:
172 const util = require('util');
174 console.log(util.inspect(util, { showHidden: true, depth: null }));
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()`.
180 ### Customizing `util.inspect` colors
184 Color output (if enabled) of `util.inspect` is customizable globally
185 via `util.inspect.styles` and `util.inspect.colors` objects.
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:
197 * `special` - only function at this time (cyan)
198 * `name` (intentionally no styling)
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.
204 ### Custom `inspect()` function on Objects
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:
211 const util = require('util');
213 var obj = { name: 'nate' };
214 obj.inspect = function(depth) {
215 return `{${this.name}}`;
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:
225 var obj = { foo: 'this will not show up in the inspect() output' };
226 obj.inspect = function(depth) {
227 return { bar: 'baz' };
233 ## util.isArray(object)
235 Stability: 0 - Deprecated
237 Internal alias for [`Array.isArray`][].
239 Returns `true` if the given "object" is an `Array`. `false` otherwise.
241 const util = require('util');
245 util.isArray(new Array)
250 ## util.isBoolean(object)
252 Stability: 0 - Deprecated
254 Returns `true` if the given "object" is a `Boolean`. `false` otherwise.
256 const util = require('util');
262 util.isBoolean(false)
265 ## util.isBuffer(object)
267 Stability: 0 - Deprecated
269 Use `Buffer.isBuffer()` instead.
271 Returns `true` if the given "object" is a `Buffer`. `false` otherwise.
273 const util = require('util');
275 util.isBuffer({ length: 0 })
279 util.isBuffer(new Buffer('hello world'))
282 ## util.isDate(object)
284 Stability: 0 - Deprecated
286 Returns `true` if the given "object" is a `Date`. `false` otherwise.
288 const util = require('util');
290 util.isDate(new Date())
293 // false (without 'new' returns a String)
297 ## util.isError(object)
299 Stability: 0 - Deprecated
301 Returns `true` if the given "object" is an [`Error`][]. `false` otherwise.
303 const util = require('util');
305 util.isError(new Error())
307 util.isError(new TypeError())
309 util.isError({ name: 'Error', message: 'an error occurred' })
312 ## util.isFunction(object)
314 Stability: 0 - Deprecated
316 Returns `true` if the given "object" is a `Function`. `false` otherwise.
318 const util = require('util');
321 var Bar = function() {};
330 ## util.isNull(object)
332 Stability: 0 - Deprecated
334 Returns `true` if the given "object" is strictly `null`. `false` otherwise.
336 const util = require('util');
340 util.isNull(undefined)
345 ## util.isNullOrUndefined(object)
347 Stability: 0 - Deprecated
349 Returns `true` if the given "object" is `null` or `undefined`. `false` otherwise.
351 const util = require('util');
353 util.isNullOrUndefined(0)
355 util.isNullOrUndefined(undefined)
357 util.isNullOrUndefined(null)
360 ## util.isNumber(object)
362 Stability: 0 - Deprecated
364 Returns `true` if the given "object" is a `Number`. `false` otherwise.
366 const util = require('util');
370 util.isNumber(Infinity)
377 ## util.isObject(object)
379 Stability: 0 - Deprecated
381 Returns `true` if the given "object" is strictly an `Object` __and__ not a
382 `Function`. `false` otherwise.
384 const util = require('util');
392 util.isObject(function(){})
395 ## util.isPrimitive(object)
397 Stability: 0 - Deprecated
399 Returns `true` if the given "object" is a primitive type. `false` otherwise.
401 const util = require('util');
405 util.isPrimitive('foo')
407 util.isPrimitive(false)
409 util.isPrimitive(null)
411 util.isPrimitive(undefined)
415 util.isPrimitive(function() {})
417 util.isPrimitive(/^$/)
419 util.isPrimitive(new Date())
422 ## util.isRegExp(object)
424 Stability: 0 - Deprecated
426 Returns `true` if the given "object" is a `RegExp`. `false` otherwise.
428 const util = require('util');
430 util.isRegExp(/some regexp/)
432 util.isRegExp(new RegExp('another regexp'))
437 ## util.isString(object)
439 Stability: 0 - Deprecated
441 Returns `true` if the given "object" is a `String`. `false` otherwise.
443 const util = require('util');
449 util.isString(String('foo'))
454 ## util.isSymbol(object)
456 Stability: 0 - Deprecated
458 Returns `true` if the given "object" is a `Symbol`. `false` otherwise.
460 const util = require('util');
466 util.isSymbol(Symbol('foo'))
469 ## util.isUndefined(object)
471 Stability: 0 - Deprecated
473 Returns `true` if the given "object" is `undefined`. `false` otherwise.
475 const util = require('util');
480 util.isUndefined(foo)
482 util.isUndefined(null)
487 Output with timestamp on `stdout`.
489 require('util').log('Timestamped message.');
493 Stability: 0 - Deprecated: Use `console.log` instead.
495 Deprecated predecessor of `console.log`.
497 ## util.pump(readableStream, writableStream[, callback])
499 Stability: 0 - Deprecated: Use readableStream.pipe(writableStream)
501 Deprecated predecessor of `stream.pipe()`.
505 Stability: 0 - Deprecated: Use console.log() instead.
507 Deprecated predecessor of `console.log`.
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