util module
The util module provides some general-purpose utilities.
require('util')
statement.- Functions
-
- util.format()
- util.inherits()
- util.inspect()
- util.isArray()
- util.isBoolean()
- util.isBuffer()
- util.isDate()
- util.isFunction()
- util.isError()
- util.isNamedNodeMap()
- util.isNodeList()
- util.isNode()
- util.isNull()
- util.isNullOrUndefined()
- util.isNumber()
- util.isObject()
- util.isPrimitive()
- util.isRegExp()
- util.isString()
- util.isSymbol()
- util.isUndefined()
- util.promisify()
- util.safeTypeOf()
- Properties
util.format()
Returns a formatted string when you use the first argument as a printf
like
format.
- Syntax
util.format(format[,…])
- Parameters
-
- format
- A
printf
like string that contains zero or more placeholders.
- Guidelines
-
The util.format() API returns a formatted string when you use the first argument as a
printf
like format. Each placeholder is replaced with the converted value from its corresponding argument. The following placeholders are supported.%s
- String
%d
- Number (both integer and float).
%j
- JSON. Replaced with the string
'[Circular]'
if the argument contains circular references. %%
- Single percent sign (%). This format does not use up an argument.
If the placeholder does not have a corresponding argument, the placeholder is not replaced.util.format('%s:%s', 'foo') ; // 'foo:%s'
If more arguments than placeholders exist, the extra arguments are converted to strings with util.inspect() and these strings are concatenated, delimited by a space.util.format('%s:%s', 'foo', 'bar', 'baz'); // 'foo:bar baz'
If the first argument is not a format string, util.format() returns a string that is the concatenation of all its arguments that are separated by spaces. Each argument is converted to a string with util.inspect().util.format(1,2,3); // '1 2 3'
util.inherits()
Inherit the prototype methods from one constructor into another. The prototype of constructor is set to a new object that is created from the superConstructor.
- Syntax
util.inherits(constructor,superConstructor)
- Parameters
-
- constructor
- The constructor object that inherits the prototype methods of another constructor.
- superConstructor
- The object with the prototype methods to inherit.
util.inspect()
Return a string representation of an object, which is useful for debugging.
- Syntax
util.inspect(object[,options])
- Parameters
-
- object
- The item to inspect.
- options
- Options that change the way that an object is inspected.
- Guidelines
-
The util.inspect() API returns a string representation of an object. The options object can be passed that alters certain aspects of the formatted string.
showHidden
- If
true
, then the nonenumerable properties of the object are shown too. Defaults tofalse
. depth
- Tells inspect how many times to iterate while formatting the object. This option is useful for
inspecting large complicated objects. Defaults to 2. To do make it iterate indefinitely, pass
null
. customInspect
- If
false
, then custominspect(depth, opts)
functions that are defined on the objects that are being inspected are not called. Defaults totrue
. showProxy
- If
true
, objects and functions that areProxy
objects are introspected to show theirtarget
andhandler
objects. Defaults tofalse
. maxArrayLength
- Specifies the maximum number of array and
TypedArray
elements to include when formatting. Defaults to 100. Set tonull
to show all array elements. Set to 0 or negative to show no array elements. breakLength
- Specifies the length at which the keys for an object are split across multiple lines. Set to
Infinity
to format an object as a single line. Defaults to 60.
- Examples
-
Inspect all properties of the util object.
var util = require('util'); console.log(util.inspect(util, { showHidden: true, depth: null }));
Values can supply their own custom
inspect(depth, opts)
functions. When called, they receive the current depth in the recursive inspection and the options object passed to util.inspect().Objects also can define their owninspect(depth)
function that util.inspect() starts and they start to use the result when they inspect the object.var util = require('util'); var obj = { name: 'nate' }; obj.inspect = function(depth) { return '{' + this.name + '}'; } util.inspect(obj); // "{nate}"
Return another Object entirely and the returned String is formatted according to the returned Object. This action is similar to how JSON.stringify() works.var obj = { foo: 'this will not show up in the inspect() output; }; obj.inspect = function(depth) { return { bar: 'baz' }; }; util.inspect(obj); // "{bar: 'baz' }"
util.inspect.custom
A property that can be used to declare custom inspect functions.
- Syntax
util.inspect.custom
- Guidelines
-
const util = require('util'); const obj = { foo: 'this will not show up in the inspect() output' }; obj[util.inspect.custom] = (depth) => { return { bar: 'baz' }; }; util.inspect(obj); // Returns: "{ bar: 'baz' }"
util.inspect.defaultOptions
Sets the value of the default options that are used by the util.inspect() API.
- Syntax
util.inspect.defaultOptions.options
- Parameters
-
- options
- Options that change the way that an object is inspected. The supported options are the same as the options in the util.inspect() API. It is set to an object when one or more valid util.inspect() options are specified.
- Guidelines
- The util.inspect.defaultOptions allows customization of the default options that are used by the util.inspect() API. Customization is useful for APIs like console.log() or util.format() that implicitly call into util.inspect().
- Example
-
const util = require('util'); const arr = Array(101).fill(0); console.log(arr); // logs the truncated array util.inspect.defaultOptions.maxArrayLength = null; console.log(arr); // logs the full array
util.isArray()
Returns true
if the specified object is an array. Otherwise, returns
false
.
- Syntax
util.isArray(object)
- Parameters
-
- object
- The item to check.
- Example
-
var util = require('util'); util.isArray([]); // true util.isArray(new Array); // true util.isArray({}); // false
util.isBoolean()
Returns true
if the specified object is a Boolean. Otherwise, returns
false
.
- Syntax
util.isBoolean(object
- Parameters
-
- object
- The item to check.
- Example
-
const util = require('util'); util.isBoolean(1); // Returns: false util.isBoolean(0); // Returns: false util.isBoolean(false); // Returns: true
util.isBuffer()
Returns true
if the specified object is a Buffer. Otherwise, returns
false
.
- Syntax
util.isBuffer(object
- Parameters
-
- object
- The item to check.
- Example
-
const util = require('util'); util.isBuffer({ length: 0 }); // Returns: false util.isBuffer([]); // Returns: false util.isBuffer(Buffer.from('hello world')); // Returns: true
util.isDate()
- Syntax
util.isDate(object
- Parameters
-
- object
- The item to check.
- Example
-
var util = require('util'); util.isDate(new Date()); // true util.isDate(Date()); // false (without a "new", it returns a string) util.isDate({}); // false
util.isError()
Returns true
if the specified object is a function. Otherwise, returns
false
.
- Syntax
util.isError(object
- Parameters
-
- object
- The item to check.
- Example
-
var util = require('util'); util.isError(new Error()); // true util.isError(new TypeError()); // true util.isError(); // false util.isError({ name: 'Error' , message: 'an error occurred'}); // false
util.isFunction()
- Syntax
util.isFunction(object
- Parameters
-
- object
- The item to check.
- Example
-
const util = require('util'); function Foo() {} const Bar = () => {}; util.isFunction({}); // Returns: false util.isFunction(Foo); // Returns: true util.isFunction(Bar); // Returns: true
util.isNamedNodeMap()
Returns true
if the object is an instance of a DOM
NamedNodeMap object. Otherwise, returns false
.
- Syntax
util.isNamedNodeMap(object
- Parameters
-
- object
- The item to check.
util.isNode()
Returns true
if the object is a DOM Node object. Otherwise,
returns false
.
- Syntax
util.isNode(object
- Parameters
-
- object
- The item to check.
- Example
-
function print(obj) { if (util.isString(obj)) { console.info(obj); } else if (util.isNode(obj)) { console.info(XML.stringify(obj)); } }
util.isNodeList()
Returns true
if the object is a DOM NodeList object.
Otherwise, returns false
.
- Syntax
util.isNodeList(object
- Parameters
-
- object
- The item to check.
util.isNull()
Returns true
if the specified object is strictly null
.
Otherwise, returns false
.
- Syntax
util.isNull(object
- Parameters
-
- object
- The item to check.
- Example
-
const util = require('util'); util.isNull(0); // Returns: false util.isNull(undefined); // Returns: false util.isNull(null); // Returns: true
util.isNullOrUndefined()
Returns true
if the specified object is null
or
undefined
. Otherwise, returns false
.
- Syntax
util.isNullOrUndefined(object
- Parameters
-
- object
- The item to check.
- Example
-
const util = require('util'); util.isNullOrUndefined(0); // Returns: false util.isNullOrUndefined(undefined); // Returns: true util.isNullOrUndefined(null); // Returns: true
util.isNumber()
Returns true
if the specified object is a number. Otherwise, returns
false
.
- Syntax
util.isNumber(object
- Parameters
-
- object
- The item to check.
- Example
-
const util = require('util'); util.isNumber(false); // Returns: false util.isNumber(Infinity); // Returns: true util.isNumber(0); // Returns: true util.isNumber(NaN); // Returns: true
util.isObject()
Returns true
if the specified object is an object and not a function. Otherwise,
returns false
.
- Syntax
util.isObject(object
- Parameters
-
- object
- The item to check.
- Example
-
const util = require('util'); util.isObject(5); // Returns: false util.isObject(null); // Returns: false util.isObject({}); // Returns: true util.isObject(function() {}); // Returns: false
util.isPrimitive()
Returns true if the specified object is a primitive type. Otherwise, returns
false
.
- Syntax
util.isPrimitive(object
- Parameters
-
- object
- The item to check.
- Example
-
const util = require('util'); util.isPrimitive(5); // Returns: true util.isPrimitive('foo'); // Returns: true util.isPrimitive(false); // Returns: true util.isPrimitive(null); // Returns: true util.isPrimitive(undefined); // Returns: true util.isPrimitive({}); // Returns: false util.isPrimitive(function() {}); // Returns: false util.isPrimitive(/^$/); // Returns: false util.isPrimitive(new Date()); // Returns: false
util.isRegExp()
Returns true
if the specified object is a RegExp. Otherwise,
returns false
.
- Syntax
util.isRegExp(object
- Parameters
-
- object
- The item to check.
- Example
-
var util = require('util'); util.isRegExp(/some regexp/); // Returns: true util.isRegExp(new RegExp('another regexp')); // Returns: true util.isRegExp({}); // Returns: false
util.isString()
Returns true
if the specified object is a string. Otherwise, returns
false
.
- Syntax
util.isString(object
- Parameters
-
- object
- The item to check.
- Example
-
const util = require('util'); util.isString(''); // Returns: true util.isString('foo'); // Returns: true util.isString(String('foo')); // Returns: true util.isString(5); // Returns: false
util.isSymbol()
Returns true
if the specified object is a symbol. Otherwise, returns
false
.
- Syntax
util.isSymbol(object
- Parameters
-
- object
- The item to check.
- Example
-
const util = require('util'); util.isSymbol(5); // Returns: false util.isSymbol('foo'); // Returns: false util.isSymbol(Symbol('foo')); // Returns: true
util.isUndefined()
Returns true
if the specified object is undefined
. Otherwise,
returns false
.
- Syntax
util.isUndefined(object
- Parameters
-
- object
- The item to check.
- Example
-
const util = require('util'); const foo = undefined; util.isUndefined(5); // Returns: false util.isUndefined(foo); // Returns: true util.isUndefined(null); // Returns: false
util.promisify()
Returns a version that returns promises.
- Syntax
util.promisify(original)
- Parameters
-
- original
- An asynchronous function.
- Guidelines
- The util.promisify() API uses the original attribute as an
asynchronous function where the last parameter is a common callback in the format of
function(error,data)
and returns a version that returns promises. - Example
-
const util = require('util'); const fs = require('fs'); const readFile = util.promisify(fs.readFile); async function callReadFile() { const data = await readFile("temporary:///my_file"); console.notice(data.toString()); }; callReadFile();
util.safeTypeOf()
Returns the object type.
- Syntax
util.safeTypeOf(object)
- Parameters
-
- object
- The item to check.
- Example
-
util.safeTypeOf(null); // 'null' util.safeTypeOf(undefined); // 'undefined' util.safeTypeOf({a: 4}); // 'object' util.safeTypeOf([1, 2, 3]); // 'array' util.safeTypeOf(arguments); // 'arguments' util.safeTypeOf(new ReferenceError); // 'error' util.safeTypeOf(new Date); // 'date' util.safeTypeOf(/a-z/); // 'regexp' util.safeTypeOf(Math); // 'math' util.safeTypeOf(JSON); // 'json' util.safeTypeOf(new Number(4)); // 'number' util.safeTypeOf(new String("abc")); // 'string' util.safeTypeOf(new Boolean(true)); // 'boolean' util.safeTypeOf(4); // 'number' util.safeTypeOf("abc"); // 'string' util.safeTypeOf(true); // 'boolean' util.safeTypeOf(false); // 'boolean' util.safeTypeOf(Infinity); // 'number' util.safeTypeOf(NaN); // 'number' util.safeTypeOf(headers.current.remove); // 'function' util.safeTypeOf(XML.parse('<a>b</a>')) // 'document' util.safeTypeOf(XML.parse('<a>b</a>').getElementsByTagName('a')) // 'nodelist' util.safeTypeOf(XML.toNodeList(XML.parse('<a>b</a>'))) // 'nodelist'