require('util')
callbackify
as of v8.2.0
debuglog
as of v0.11.3
deprecate
as of v0.8.0
format
as of v0.5.3 :: v8.4.0
inspect
as of v0.3.0 :: v6.6.0
isDeepStrictEqual
as of v9.0.0
promisify
as of v8.0.0
Turn an asynchronous function that takes a Node style callback and returns an asynchronous function that returns a Promise
const fs = require('fs') const { promisify } = require('util') const readFile = promisify(fs.readFile) readFile('./package.json') .then(JSON.parse) .catch(() => ({}))
Introduced in v8.0.0
fn nscb → fn → P
Some genius tweeter cracked the code of turning a function that takes a Node style callback and turning it into a function that returns a Promise.
Turn an asynchronous function that returns a Promise and returns a function that takes a Node style callback.
const fetch = require('whatwg-fetch') const { callbackify } = require('util') const request = callbackify(fetch) request('http://api.openweathermap.org/data/2.5/weather?zip=94040,us', (err, data) => { if (err) return const { weather: { description } } = JSON.parse(data) })
Introduced in v8.0.0
fn p → fnnscb
Compares two objects and returns true if the structures and values are the same deeply
const { isDeepStrictEqual } = require('util') const fn = () => {} const v1 = { a: { b: { c: true, d: 'hi' }, e: 1 }, [symbol]: fn } const v2 = { a: { b: { c: true, d: 'hi' }, e: 1 }, [symbol]: fn } const v3 = { a: { b: { c: true, d: 'bye' }, e: 1 }, [symbol]: fn } isDeepStrictEqaul(v1, v2) //true isDeepStrictEqaul(v1, v3) //false
Introduced in v9.0.0
o → o → bool
Long existed in core, recently exposed as util.
util,assert: expose util.isDeepStrictEqual()
Provide `util.isDeepStrictEqual()` that works like `assert.deepStrictEqual()` but returns a boolean rather than throwing an error.
Several userland modules have needed this functionality and implemented it independently. This functionality already exists in Node.js core, so this exposes it for use by modules. Modules that have needed this functionality include `lodash`, `concordance` (used by `ava`), and `qunit`.
Creates a function that writes to stderr when the NODE_DEBUG environment variable matches the section provided to debuglog
const { debuglog } = require('util') const intLog = debuglog('integration') intLog('I only log when `NODE_DEBUG` is set to `integration`.')
Introduced in v0.11.3
section → fnM
In addition to conditionally logging the passed arguments to stderr, it prepends the log with the name of the section and the pid.
Multiple sections can be specified for the NODE_DEBUG environment variable via a comma separated list:
NODE_DEBUG=dev,int,stg
Formats a string based on printf like syntaxes
const { format } = require('util') const theFormat = [{ album: 'interventions and lullabies', awesomeLevel: 11 }, { album: "dog problems", awesomeLevel: 7 }] format('%s is awesome * %d', theFormat[0].album, theFormat[0].awesomeLevel, JSON.stringify(theFormat), theFormat
Introduced in v0.5.3
str → ...vals → void M
The 1st arg is a string with 0 or more tokens. Each token is replaced with the value from the corresponding arg.
Supported placeholders are:
%s - String.
%d - Number (integer or float).
%i - Integer.
%f - Float.
%j - JSON.
%o - Object.
%O - Object.
%% - single percent sign ('%').
%j may be replaced with the string '[Circular]' if the argument contains circular references.
%o is similar to inspect(o, {
showHidden: true,
depth: 4,
showProxy: true
})
%O - Object. is similar to inspect(o, {})
Returns a string representation of object. Primarily useful for debugging. Additional options may be passed that can alter aspects of the formatted string.
const { inspect } = require('util') const theFormat = [{ album: 'interventions and lullabies', awesomeLevel: 11 }, { album: "dog problems", awesomeLevel: 7 }] inspect(theFormat, {})
Introduced in v0.3.0
obj → opts → str
showHidden(false):
show the non-enumerable symbols and properties in the result.
depth(2):
The number of recursions while formatting the object. To make it recurse indefinitely pass null.
colors(false):
If true, the output will be styled with ANSI color codes. Colors are customizable.
customInspect(true):
If false, then custom inspect(depth, opts) fns exported on the object being inspected will not be called.
showProxy(false):
shows Proxy target and handler objects.
maxArrayLength(100):
The maximum number of array and TypedArray elements to include when formatting. Set to null to show all elements. Set to 0 or negative to show no elements.
breakLength(60):
The length at which an object's keys are split across multiple lines. Set to Infinity to format an object as a single line.
Wraps a function such that when called the first time in a process, emits a 'warning' event that is logged to stderr by default
const { deprecate } = require('util') const oldFn = deprecate( () => 'Wicked Smaht!', '`oldFn` is deprecated. Use `newFn` instead' ) oldFn() // 'Wicked Smaht!' err:: `oldFn` is deprecated. Use `newFn` instead
Introduced in v0.8.0
fn → str → fnM
If either the --no-deprecation or --no-warnings flags are set, the deprecate method does nothing.
If the --trace-deprecation or --trace-warnings flags are set, a warning and stack trace are printed to stderr the first time the deprecated function is called.
If the --throw-deprecation flag is set, then an exception will be thrown when the deprecated function is called.
The --throw-deprecation flag take precedence over --trace-deprecation.
_extend 6.0.0
debug 0.11.3
error 0.11.3
isArray 4.0.0
isBoolean 4.0.0
isBuffer 4.0.0
isDate 4.0.0
isError 4.0.0
isFunction 4.0.0
isNull 4.0.0
isNullOrUndefined 4.0.0
Object.assign or { ... }
console.error
console.error
Array.isArray
[true, false].includes(val)
Buffer.isBuffer
val === null
val == null
isNumber 4.0.0
isObject 4.0.0
isPrimitive 4.0.0
isRegExp 4.0.0
isString 4.0.0
isSymbol 4.0.0
isUndefined 4.0.0
log 6.0.0
print 0.11.3
puts 0.11.3
val === void 0
Use a 3rd party module instead
console.log
console.log
Judging from some TSC minutes from February 2015 and discussion in a pull request from the same month, it seems like the reasoning is something like this:
Hey, looks like util.isObject() returns false for a function. That isn't correct. A function is an object. It should return true. But making that change potentially breaks huge portions of the Node ecosystem. Think of all those modules on npm that might be dependent on that behavior. In order to not risk breaking the ecosystem in surprising ways, we'd have to somehow get a ton of people to review their code. And the breaking change would be totally backwards incompatible. All for a convenience function that doesn't even really belong in core and is easily provided by userland modules. (See, for example, core-util-is.) Rather than introduce a breaking change and a semver major bump just to fix util.isObject(), let's do what should have been done in the first place and don't even have it in core.