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 below.
166 - `customInspect` - if `false`, then custom `inspect(depth, opts)` functions
167 defined on the objects being inspected won't be called. Defaults to `true`.
169 Example of inspecting all properties of the `util` object:
171 const util = require('util');
173 console.log(util.inspect(util, { showHidden: true, depth: null }));
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()`.
179 ### Customizing `util.inspect` colors
183 Color output (if enabled) of `util.inspect` is customizable globally
184 via `util.inspect.styles` and `util.inspect.colors` objects.
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:
196 * `special` - only function at this time (cyan)
197 * `name` (intentionally no styling)
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.
203 ### Custom `inspect()` function on Objects
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:
210 const util = require('util');
212 var obj = { name: 'nate' };
213 obj.inspect = function(depth) {
214 return `{${this.name}}`;
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:
224 var obj = { foo: 'this will not show up in the inspect() output' };
225 obj.inspect = function(depth) {
226 return { bar: 'baz' };
232 ## util.isArray(object)
234 Stability: 0 - Deprecated
236 Internal alias for [`Array.isArray`][].
238 Returns `true` if the given "object" is an `Array`. `false` otherwise.
240 const util = require('util');
244 util.isArray(new Array)
249 ## util.isBoolean(object)
251 Stability: 0 - Deprecated
253 Returns `true` if the given "object" is a `Boolean`. `false` otherwise.
255 const util = require('util');
261 util.isBoolean(false)
264 ## util.isBuffer(object)
266 Stability: 0 - Deprecated
268 Use `Buffer.isBuffer()` instead.
270 Returns `true` if the given "object" is a `Buffer`. `false` otherwise.
272 const util = require('util');
274 util.isBuffer({ length: 0 })
278 util.isBuffer(new Buffer('hello world'))
281 ## util.isDate(object)
283 Stability: 0 - Deprecated
285 Returns `true` if the given "object" is a `Date`. `false` otherwise.
287 const util = require('util');
289 util.isDate(new Date())
292 // false (without 'new' returns a String)
296 ## util.isError(object)
298 Stability: 0 - Deprecated
300 Returns `true` if the given "object" is an [`Error`][]. `false` otherwise.
302 const util = require('util');
304 util.isError(new Error())
306 util.isError(new TypeError())
308 util.isError({ name: 'Error', message: 'an error occurred' })
311 ## util.isFunction(object)
313 Stability: 0 - Deprecated
315 Returns `true` if the given "object" is a `Function`. `false` otherwise.
317 const util = require('util');
320 var Bar = function() {};
329 ## util.isNull(object)
331 Stability: 0 - Deprecated
333 Returns `true` if the given "object" is strictly `null`. `false` otherwise.
335 const util = require('util');
339 util.isNull(undefined)
344 ## util.isNullOrUndefined(object)
346 Stability: 0 - Deprecated
348 Returns `true` if the given "object" is `null` or `undefined`. `false` otherwise.
350 const util = require('util');
352 util.isNullOrUndefined(0)
354 util.isNullOrUndefined(undefined)
356 util.isNullOrUndefined(null)
359 ## util.isNumber(object)
361 Stability: 0 - Deprecated
363 Returns `true` if the given "object" is a `Number`. `false` otherwise.
365 const util = require('util');
369 util.isNumber(Infinity)
376 ## util.isObject(object)
378 Stability: 0 - Deprecated
380 Returns `true` if the given "object" is strictly an `Object` __and__ not a
381 `Function`. `false` otherwise.
383 const util = require('util');
391 util.isObject(function(){})
394 ## util.isPrimitive(object)
396 Stability: 0 - Deprecated
398 Returns `true` if the given "object" is a primitive type. `false` otherwise.
400 const util = require('util');
404 util.isPrimitive('foo')
406 util.isPrimitive(false)
408 util.isPrimitive(null)
410 util.isPrimitive(undefined)
414 util.isPrimitive(function() {})
416 util.isPrimitive(/^$/)
418 util.isPrimitive(new Date())
421 ## util.isRegExp(object)
423 Stability: 0 - Deprecated
425 Returns `true` if the given "object" is a `RegExp`. `false` otherwise.
427 const util = require('util');
429 util.isRegExp(/some regexp/)
431 util.isRegExp(new RegExp('another regexp'))
436 ## util.isString(object)
438 Stability: 0 - Deprecated
440 Returns `true` if the given "object" is a `String`. `false` otherwise.
442 const util = require('util');
448 util.isString(String('foo'))
453 ## util.isSymbol(object)
455 Stability: 0 - Deprecated
457 Returns `true` if the given "object" is a `Symbol`. `false` otherwise.
459 const util = require('util');
465 util.isSymbol(Symbol('foo'))
468 ## util.isUndefined(object)
470 Stability: 0 - Deprecated
472 Returns `true` if the given "object" is `undefined`. `false` otherwise.
474 const util = require('util');
479 util.isUndefined(foo)
481 util.isUndefined(null)
486 Output with timestamp on `stdout`.
488 require('util').log('Timestamped message.');
492 Stability: 0 - Deprecated: Use `console.log` instead.
494 Deprecated predecessor of `console.log`.
496 ## util.pump(readableStream, writableStream[, callback])
498 Stability: 0 - Deprecated: Use readableStream.pipe(writableStream)
500 Deprecated predecessor of `stream.pipe()`.
504 Stability: 0 - Deprecated: Use console.log() instead.
506 Deprecated predecessor of `console.log`.
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