node:util module provides utility functions that support the needs of Node.js internal APIs. Many of these utilities are useful for application and module developers as well.
Installation
Key Functions
util.promisify(original)
Converts a callback-based function to a Promise-based function. Parameters:original- A function following the error-first callback style
util.callbackify(original)
Converts anasync function or Promise-returning function to a callback style function.
Parameters:
original- An async function or function that returns a Promise
util.inspect(object[, options])
Returns a string representation of an object for debugging purposes. Parameters:object- The object to inspectoptions- Optional formatting optionsshowHidden- Show non-enumerable properties (default: false)depth- Recursion depth (default: 2)colors- Colorize output (default: false)compact- Compact output formatmaxArrayLength- Maximum array elements to showbreakLength- Length at which to break output
util.format(format[, …args])
Returns a formatted string using printf-like format specifiers. Format specifiers:%s- String%d- Number%i- Integer%f- Floating point%j- JSON%o- Object%%- Literal percent sign
util.types
Provides type checking utilities for various JavaScript and Node.js types.Common Type Checks
Available Type Checks
isAnyArrayBuffer(value)isArgumentsObject(value)isArrayBuffer(value)isArrayBufferView(value)isAsyncFunction(value)isBigInt64Array(value)isBigUint64Array(value)isBooleanObject(value)isBoxedPrimitive(value)isDataView(value)isDate(value)isExternal(value)isFloat32Array(value)isFloat64Array(value)isGeneratorFunction(value)isGeneratorObject(value)isInt8Array(value)isInt16Array(value)isInt32Array(value)isMap(value)isMapIterator(value)isModuleNamespaceObject(value)isNativeError(value)isNumberObject(value)isPromise(value)isProxy(value)isRegExp(value)isSet(value)isSetIterator(value)isSharedArrayBuffer(value)isStringObject(value)isSymbolObject(value)isTypedArray(value)isUint8Array(value)isUint8ClampedArray(value)isUint16Array(value)isUint32Array(value)isWeakMap(value)isWeakSet(value)
Debugging Utilities
util.debuglog(section[, callback])
Creates a function that conditionally writes debug messages based on theNODE_DEBUG environment variable.
Example: