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:
45 FOO 3245: hello from foo [123]
48 where `3245` is the process id. If it is not run with that
49 environment variable set, then it will not print anything.
51 You may separate multiple `NODE_DEBUG` environment variables with a
52 comma. For example, `NODE_DEBUG=fs,net,tls`.
54 ## util.deprecate(function, string)
56 Marks that a method should not be used any more.
59 const util = require('util');
61 exports.puts = util.deprecate(function() {
62 for (var i = 0, len = arguments.length; i < len; ++i) {
63 process.stdout.write(arguments[i] + '\n');
65 }, 'util.puts: Use console.log instead');
68 It returns a modified function which warns once by default.
70 If `--no-deprecation` is set then this function is a NO-OP. Configurable
71 at run-time through the `process.noDeprecation` boolean (only effective
72 when set before a module is loaded.)
74 If `--trace-deprecation` is set, a warning and a stack trace are logged
75 to the console the first time the deprecated API is used. Configurable
76 at run-time through the `process.traceDeprecation` boolean.
78 If `--throw-deprecation` is set then the application throws an exception
79 when the deprecated API is used. Configurable at run-time through the
80 `process.throwDeprecation` boolean.
82 `process.throwDeprecation` takes precedence over `process.traceDeprecation`.
86 Stability: 0 - Deprecated: Use console.error() instead.
88 Deprecated predecessor of `console.error`.
90 ## util.format(format[, ...])
92 Returns a formatted string using the first argument as a `printf`-like format.
94 The first argument is a string that contains zero or more *placeholders*.
95 Each placeholder is replaced with the converted value from its corresponding
96 argument. Supported placeholders are:
99 * `%d` - Number (both integer and float).
100 * `%j` - JSON. Replaced with the string `'[Circular]'` if the argument
101 contains circular references.
102 * `%%` - single percent sign (`'%'`). This does not consume an argument.
104 If the placeholder does not have a corresponding argument, the placeholder is
108 util.format('%s:%s', 'foo'); // 'foo:%s'
111 If there are more arguments than placeholders, the extra arguments are
112 coerced to strings (for objects and symbols, `util.inspect()` is used)
113 and then concatenated, delimited by a space.
116 util.format('%s:%s', 'foo', 'bar', 'baz'); // 'foo:bar baz'
119 If the first argument is not a format string then `util.format()` returns
120 a string that is the concatenation of all its arguments separated by spaces.
121 Each argument is converted to a string with `util.inspect()`.
124 util.format(1, 2, 3); // '1 2 3'
127 ## util.inherits(constructor, superConstructor)
129 Inherit the prototype methods from one [constructor][] into another. The
130 prototype of `constructor` will be set to a new object created from
133 As an additional convenience, `superConstructor` will be accessible
134 through the `constructor.super_` property.
137 const util = require('util');
138 const EventEmitter = require('events');
140 function MyStream() {
141 EventEmitter.call(this);
144 util.inherits(MyStream, EventEmitter);
146 MyStream.prototype.write = function(data) {
147 this.emit('data', data);
150 var stream = new MyStream();
152 console.log(stream instanceof EventEmitter); // true
153 console.log(MyStream.super_ === EventEmitter); // true
155 stream.on('data', (data) => {
156 console.log(`Received data: "${data}"`);
158 stream.write('It works!'); // Received data: "It works!"
161 ## util.inspect(object[, options])
163 Return a string representation of `object`, which is useful for debugging.
165 An optional *options* object may be passed that alters certain aspects of the
168 - `showHidden` - if `true` then the object's non-enumerable and symbol
169 properties will be shown too. Defaults to `false`.
171 - `depth` - tells `inspect` how many times to recurse while formatting the
172 object. This is useful for inspecting large complicated objects. Defaults to
173 `2`. To make it recurse indefinitely pass `null`.
175 - `colors` - if `true`, then the output will be styled with ANSI color codes.
176 Defaults to `false`. Colors are customizable, see [Customizing
177 `util.inspect` colors][].
179 - `customInspect` - if `false`, then custom `inspect(depth, opts)` functions
180 defined on the objects being inspected won't be called. Defaults to `true`.
182 Example of inspecting all properties of the `util` object:
185 const util = require('util');
187 console.log(util.inspect(util, { showHidden: true, depth: null }));
190 Values may supply their own custom `inspect(depth, opts)` functions, when
191 called they receive the current depth in the recursive inspection, as well as
192 the options object passed to `util.inspect()`.
194 ### Customizing `util.inspect` colors
198 Color output (if enabled) of `util.inspect` is customizable globally
199 via `util.inspect.styles` and `util.inspect.colors` objects.
201 `util.inspect.styles` is a map assigning each style a color
202 from `util.inspect.colors`.
203 Highlighted styles and their default values are:
211 * `special` - only function at this time (cyan)
212 * `name` (intentionally no styling)
214 Predefined color codes are: `white`, `grey`, `black`, `blue`, `cyan`,
215 `green`, `magenta`, `red` and `yellow`.
216 There are also `bold`, `italic`, `underline` and `inverse` codes.
218 ### Custom `inspect()` function on Objects
222 Objects also may define their own `inspect(depth)` function which `util.inspect()`
223 will invoke and use the result of when inspecting the object:
226 const util = require('util');
228 var obj = { name: 'nate' };
229 obj.inspect = function(depth) {
230 return `{${this.name}}`;
237 You may also return another Object entirely, and the returned String will be
238 formatted according to the returned Object. This is similar to how
239 `JSON.stringify()` works:
242 var obj = { foo: 'this will not show up in the inspect() output' };
243 obj.inspect = function(depth) {
244 return { bar: 'baz' };
251 ## util.isArray(object)
253 Stability: 0 - Deprecated
255 Internal alias for [`Array.isArray`][].
257 Returns `true` if the given "object" is an `Array`. `false` otherwise.
260 const util = require('util');
264 util.isArray(new Array)
270 ## util.isBoolean(object)
272 Stability: 0 - Deprecated
274 Returns `true` if the given "object" is a `Boolean`. `false` otherwise.
277 const util = require('util');
283 util.isBoolean(false)
287 ## util.isBuffer(object)
289 Stability: 0 - Deprecated
291 Use `Buffer.isBuffer()` instead.
293 Returns `true` if the given "object" is a `Buffer`. `false` otherwise.
296 const util = require('util');
298 util.isBuffer({ length: 0 })
302 util.isBuffer(new Buffer('hello world'))
306 ## util.isDate(object)
308 Stability: 0 - Deprecated
310 Returns `true` if the given "object" is a `Date`. `false` otherwise.
313 const util = require('util');
315 util.isDate(new Date())
318 // false (without 'new' returns a String)
323 ## util.isError(object)
325 Stability: 0 - Deprecated
327 Returns `true` if the given "object" is an [`Error`][]. `false` otherwise.
330 const util = require('util');
332 util.isError(new Error())
334 util.isError(new TypeError())
336 util.isError({ name: 'Error', message: 'an error occurred' })
340 ## util.isFunction(object)
342 Stability: 0 - Deprecated
344 Returns `true` if the given "object" is a `Function`. `false` otherwise.
347 const util = require('util');
350 var Bar = function() {};
360 ## util.isNull(object)
362 Stability: 0 - Deprecated
364 Returns `true` if the given "object" is strictly `null`. `false` otherwise.
367 const util = require('util');
371 util.isNull(undefined)
377 ## util.isNullOrUndefined(object)
379 Stability: 0 - Deprecated
381 Returns `true` if the given "object" is `null` or `undefined`. `false` otherwise.
384 const util = require('util');
386 util.isNullOrUndefined(0)
388 util.isNullOrUndefined(undefined)
390 util.isNullOrUndefined(null)
394 ## util.isNumber(object)
396 Stability: 0 - Deprecated
398 Returns `true` if the given "object" is a `Number`. `false` otherwise.
401 const util = require('util');
405 util.isNumber(Infinity)
413 ## util.isObject(object)
415 Stability: 0 - Deprecated
417 Returns `true` if the given "object" is strictly an `Object` __and__ not a
418 `Function`. `false` otherwise.
421 const util = require('util');
429 util.isObject(function(){})
433 ## util.isPrimitive(object)
435 Stability: 0 - Deprecated
437 Returns `true` if the given "object" is a primitive type. `false` otherwise.
440 const util = require('util');
444 util.isPrimitive('foo')
446 util.isPrimitive(false)
448 util.isPrimitive(null)
450 util.isPrimitive(undefined)
454 util.isPrimitive(function() {})
456 util.isPrimitive(/^$/)
458 util.isPrimitive(new Date())
462 ## util.isRegExp(object)
464 Stability: 0 - Deprecated
466 Returns `true` if the given "object" is a `RegExp`. `false` otherwise.
469 const util = require('util');
471 util.isRegExp(/some regexp/)
473 util.isRegExp(new RegExp('another regexp'))
479 ## util.isString(object)
481 Stability: 0 - Deprecated
483 Returns `true` if the given "object" is a `String`. `false` otherwise.
486 const util = require('util');
492 util.isString(String('foo'))
498 ## util.isSymbol(object)
500 Stability: 0 - Deprecated
502 Returns `true` if the given "object" is a `Symbol`. `false` otherwise.
505 const util = require('util');
511 util.isSymbol(Symbol('foo'))
515 ## util.isUndefined(object)
517 Stability: 0 - Deprecated
519 Returns `true` if the given "object" is `undefined`. `false` otherwise.
522 const util = require('util');
527 util.isUndefined(foo)
529 util.isUndefined(null)
535 Output with timestamp on `stdout`.
537 require('util').log('Timestamped message.');
541 Stability: 0 - Deprecated: Use `console.log` instead.
543 Deprecated predecessor of `console.log`.
545 ## util.pump(readableStream, writableStream[, callback])
547 Stability: 0 - Deprecated: Use readableStream.pipe(writableStream)
549 Deprecated predecessor of `stream.pipe()`.
553 Stability: 0 - Deprecated: Use console.log() instead.
555 Deprecated predecessor of `console.log`.
557 [`Array.isArray`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
558 [constructor]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/constructor
559 [Customizing `util.inspect` colors]: #util_customizing_util_inspect_colors
560 [here]: #util_customizing_util_inspect_colors
561 [`Error`]: errors.html#errors_class_error