util
Source: lib/util.js (pure JS)
The project's central utility library — a large collection of helpers for type
checking, object/property manipulation, functional composition, collections,
strings, numbers, time, async, and more. Re-exports everything from
misc and inspect from inspect.
> This module is large; functions are grouped by theme below. Argument lists are > abbreviated — see the source for defaults.
Type checks & reflection
isObject, typeIsObject, allObjects, isClass, isNative,
isPropertyKey, isArrowFunction, isAsync, isNumeric, isIndex,
inRange, isInstanceOf(c, o), isPrototypeOf(p, o), hasPrototype,
hasBuiltIn, hasOwnProperty, hasOwn, hasProperty, hasFn,
propertyIsEnumerable, getConstructorOf, getConstructorChain. Type tables:
types, TypeIds, errors. Constructor handles: AsyncFunction,
GeneratorFunction, AsyncGeneratorFunction, TypedArray, Generator,
SetIterator, MapIterator, and their prototypes.
Object / property utilities
Object reflection wrappers: getPrototypeOf, setPrototypeOf,
getOwnPropertyNames, getOwnPropertySymbols, getOwnPropertyDescriptor(s),
defineProperty, defineProperties, seal, freeze, isSealed, isFrozen,
isExtensible, preventExtensions, assign, is, valueOf, toString,
toLocaleString.
Accessor builders: getset, getter, setter, gettersetter, modifier,
wrapGetSet, weakGetSet, getSetArgument, hasGetSet, addremovehas,
remover, getOrCreate, lookupObject, mapObject, propertyLookup,
propertyLookupHandlers, bindProperties.
Definition helpers: define, weakDefine, declare, extend, merge,
nonenumerable, enumerable, defineGetter, defineGetterSetter,
defineGettersSetters, lazyProperty, lazyProperties, observeProperties,
decorate, decorateProperty, weakAssoc.
Property/method enumeration: keys, values, entries, fromEntries, pick,
omit, properties, getPropertyNames, getProperties, getMethodNames,
getMethods, bindMethods, prototypeIterator, inherits.
Functional / composition
memoize, once, curry, chain, chainRight, chainArray, mapFunctional,
predicate, transformer, wrapFunction, catchFunction, finallyFunction,
tryFunction, tryCatch, wrapGenerator, wrapGeneratorMethods,
copyFunctionNameAndLength, setFunctionName, functionName (alias fnName),
className, getFunctionArguments, instrument, catchable.
Collections & arrays
filter, filterKeys, map, range, split, chunkArray, partitionArray,
partition, unique, uniquePred, pushUnique, push, eraseIf, inserter,
generate, arraysInCommon, arrayFacade. Set algebra: intersect,
intersection, union, difference, symmetricDifference. histogram,
mapAdapter, mapFunction, mapWrapper, weakMapper, hash.
Strings & text
stripAnsi, padAnsi, padStartAnsi, padEndAnsi, pad, padFn, trim,
abbreviate, shorten, ucfirst, lcfirst, camelize, decamelize,
decodeHTMLEntities, bytesToUTF8, codePointsToString, bufferToString,
matchAll, indexOf, searchAll. ANSI styling: ansiStyles.
Numbers & math
clamp, mod, roundTo, roundDigits, toBigInt, numericIndex,
randInt, randFloat, randStr. Curried operators: add, sub, mul,
div, pow, xor, or, and. Length/slice helpers: length, slice.
Time & dates
isoDate, toUnixTime, unixTime, fromUnixTime.
Async & scheduling
setImmediate, clearImmediate, queueMicrotask, waitFor,
waitCancellable, plus re-exported setInterval/clearInterval (from
timers).
Assertions & errors
assert, assertEqual, getSystemErrorName, getSystemErrorMap.
CLI
getOpt(options, args) — parses command-line options; showHelp(opts, exitCode)
— prints usage.
Environment & misc
isBrowser, startInteractive, Membrane(instance, obj, proto, …),
repeat, repeater, inspectSymbol.
Re-exports
inspect (from inspect), everything from misc, and
setInterval/clearInterval (from timers).
Node's util surface
format(fmt, ...args) (%s %d %i %f %j %o %O %c %%), formatWithOptions, promisify
(honours promisify.custom), callbackify, deprecate, debuglog/debug (NODE_DEBUG),
isDeepStrictEqual, parseArgs({ args, options, strict, allowPositionals }) (no tokens,
no allowNegative), TextEncoder, TextDecoder. format('%o') does not list hidden
properties such as [length], and %s of an object shows one level more than Node.
Export list
Generated by utilities/doc-api.js from the util dump of utilities/api-surface.sh: 1022 members. Edit the text above this block, not the block.
Functions: AsyncGeneratorPrototype[Symbol.toStringTag](), GeneratorPrototype[Symbol.toStringTag](), Generator[Symbol.toStringTag](), TypedArray[Symbol.species](), AsyncFunction(), Membrane(), _get_osfhandle(), _open_osfhandle(), abbreviate(), access(), add(), addremovehas(), allObjects(), and(), arrayFacade(), arrayToBitfield(), arraysInCommon(), assert(), assertEqual(), assign(), atexit(), atob(), atomToString(), atomToValue(), atos(), awaitSync(), bindMethods(), bindProperties(), bitfieldSet(), bitfieldToArray(), bits(), btoa(), bufferToString(), byteSwap(), bytesToUTF8(), camelize(), catchFunction(), catchable(), chain(), chainArray(), chainRight(), charCode(), charLength(), chmod(), chown(), chunkArray(), clamp(), classAtom(), classId(), className(), clearImmediate(), clearInterval(), clearLine(), clearScreen(), codePointsToString(), compareArrayBuffer(), concatArrayBuffer(), copyArrayBuffer(), copyFunctionNameAndLength(), curry(), daemon(), decamelize(), declare(), decodeHTMLEntities(), decorate(), decorateProperty(), define(), defineGetter(), defineGetterSetter(), defineGettersSetters(), defineProperties(), defineProperty(), dequote(), difference(), div(), dupArrayBuffer(), dupAtom(), enqueueJob(), entries(), enumerable(), eraseIf(), error(), escape(), evalBinary(), exec(), extend(), fchmod(), fchown(), fcntl(), fdatasync(), filter(), filterKeys(), finallyFunction(), findAtom(), fmemopen(), fnName(), fork(), freeAtom(), freeze(), fromEntries(), fromUnixTime(), fstat(), fsync(), ftruncate(), functionName(), futimes(), generate(), getCommandLine(), getConstructorChain(), getConstructorOf(), getEnvironment(), getExecutable(), getFileDescriptor(), getFunctionArguments(), getMethodNames(), getMethods(), getOpt(), getOptHelp(), getOrCreate(), getOwnPropertyDescriptor(), getOwnPropertyDescriptors(), getOwnPropertyNames(), getOwnPropertySymbols(), getPerformanceCounter(), getProcMaps(), getProcMounts(), getProcStat(), getProperties(), getPropertyNames(), getPrototypeChain(), getPrototypeOf(), getRelease(), getRootDirectory(), getScreenSize(), getSetArgument(), getSystemErrorMap(), getSystemErrorName(), getTypeId(), getTypeName(), getTypeStr(), getWorkingDirectory(), getegid(), geteuid(), getgid(), getpid(), getppid(), getset(), getsid(), getter(), gettersetter(), getuid(), glob(), hasBuiltIn(), hasFn(), hasGetSet(), hasOwn(), hasOwnProperty(), hasProperty(), hasPrototype(), hash(), histogram(), hrtime(), immutableClass(), importSync(), inRange(), indexOf(), inherits(), initgroups(), inserter(), inspect(), instrument(), intersect(), intersection(), is(), isArray(), isArrayBuffer(), isArrowFunction(), isAsync(), isBigDecimal(), isBigFloat(), isBigInt(), isBool(), isBrowser(), isClass(), isConstructor(), isEmptyString(), isError(), isException(), isExtensible(), isFrozen(), isFunction(), isIndex(), isInstanceOf(), isInteger(), isJobPending(), isLiveObject(), isMainModule(), isNative(), isNull(), isNumber(), isNumeric(), isObject(), isPropertyKey(), isPrototypeOf(), isRegisteredClass(), isSealed(), isString(), isSymbol(), isUncatchableError(), isUndefined(), isUninitialized(), isoDate(), keys(), kill(), lazyProperties(), lazyProperty(), lcfirst(), lchown(), length(), lineStarts(), link(), linkat(), lookupObject(), lutimes(), map(), mapAdapter(), mapFunction(), mapFunctional(), mapObject(), mapWrapper(), matchAll(), memoize(), merge(), mkstemp(), mod(), modifier(), moveCursor(), mul(), nonenumerable(), noop(), not(), numericIndex(), objectClassId(), objectOpaque(), objectRefCount(), observeProperties(), omit(), once(), or(), pad(), padAnsi(), padEndAnsi(), padFn(), padStartAnsi(), partition(), partitionArray(), pick(), pow(), preadv(), preadv2(), predicate(), preventExtensions(), promiseResult(), promiseState(), properties(), propertyIsEnumerable(), propertyLookup(), propertyLookupHandlers(), prototypeIterator(), push(), pushUnique(), pwritev(), pwritev2(), queueMicrotask(), quote(), rand(), randFloat(), randInt(), randStr(), randb(), randi(), range(), readObject(), readv(), remover(), repeat(), repeater(), requireObject(), roundDigits(), roundTo(), seal(), searchAll(), searchArrayBuffer(), searchArrayBufferLast(), setCursorPosition(), setFunctionName(), setImmediate(), setInterval(), setPrototypeOf(), setTextAttribute(), setTextColor(), setegid(), seteuid(), setgid(), setgroups(), setsid(), setter(), setuid(), shorten(), signame(), signum(), slice(), sliceArrayBuffer(), split(), srand(), startInteractive(), stoa(), strcmp(), stripAnsi(), sub(), symlink(), symlinkat(), symmetricDifference(), tempnam(), toArrayBuffer(), toBigInt(), toLocaleString(), toPointer(), toString(), toUnixTime(), transformer(), trim(), truncate(), tryCatch(), tryFunction(), ttyGetWinSize(), ttyRead(), ttySetRaw(), ttyWrite(), typeFlag(), typeIsObject(), typeName(), typeString(), ucfirst(), umask(), uname(), unescape(), union(), unique(), uniquePred(), unixTime(), unlink(), utime(), utimes(), valueOf(), valuePointer(), valueTag(), valueToAtom(), valueType(), values(), vfork(), waitCancellable(), waitFor(), watch(), weakAssoc(), weakDefine(), weakGetSet(), weakMapper(), wordexp(), wrapFunction(), wrapGenerator(), wrapGeneratorMethods(), wrapGetSet(), writeObject(), writev(), xor()
Values: AT_EMPTY_PATH = 4096, AT_SYMLINK_FOLLOW = 1024, BACKGROUND_BLUE = 16, BACKGROUND_GREEN = 32, BACKGROUND_INTENSITY = 128, BACKGROUND_RED = 64, CLOCK_BOOTTIME = 7, CLOCK_BOOTTIME_ALARM = 9, CLOCK_MONOTONIC = 1, CLOCK_MONOTONIC_COARSE = 6, CLOCK_MONOTONIC_RAW = 4, CLOCK_PROCESS_CPUTIME_ID = 2, CLOCK_REALTIME = 0, CLOCK_REALTIME_ALARM = 8, CLOCK_REALTIME_COARSE = 5, CLOCK_TAI = 11, CLOCK_THREAD_CPUTIME_ID = 3, COMMON_LVB_REVERSE_VIDEO = 16384, E2BIG = 7, EACCES = 13, EADDRINUSE = 98, EADDRNOTAVAIL = 99, EAFNOSUPPORT = 97, EAGAIN = 11, EALREADY = 114, EBADF = 9, EBADMSG = 74, EBUSY = 16, ECANCELED = 125, ECHILD = 10, ECONNABORTED = 103, ECONNREFUSED = 111, ECONNRESET = 104, EDEADLK = 35, EDESTADDRREQ = 89, EDOM = 33, EDQUOT = 122, EEXIST = 17, EFAULT = 14, EFBIG = 27, EHOSTUNREACH = 113, EIDRM = 43, EILSEQ = 84, EINPROGRESS = 115, EINTR = 4, EINVAL = 22, EIO = 5, EISCONN = 106, EISDIR = 21, ELOOP = 40, EMFILE = 24, EMLINK = 31, EMSGSIZE = 90, EMULTIHOP = 72, ENAMETOOLONG = 36, ENETDOWN = 100, ENETRESET = 102, ENETUNREACH = 101, ENFILE = 23, ENOBUFS = 105, ENODATA = 61, ENODEV = 19, ENOENT = 2, ENOEXEC = 8, ENOLCK = 37, ENOLINK = 67, ENOMEM = 12, ENOMSG = 42, ENOPROTOOPT = 92, ENOSPC = 28, ENOSR = 63, ENOSTR = 60, ENOSYS = 38, ENOTCONN = 107, ENOTDIR = 20, ENOTEMPTY = 39, ENOTSOCK = 88, ENOTSUP = 95, ENOTTY = 25, ENXIO = 6, EOPNOTSUPP = 95, EOVERFLOW = 75, EPERM = 1, EPIPE = 32, EPROTO = 71, EPROTONOSUPPORT = 93, EPROTOTYPE = 91, ERANGE = 34, EROFS = 30, ESPIPE = 29, ESRCH = 3, ESTALE = 116, ETIME = 62, ETIMEDOUT = 110, ETXTBSY = 26, EWOULDBLOCK = 11, EXDEV = 18, FD_CLOEXEC = 1, FOREGROUND_BLUE = 1, FOREGROUND_GREEN = 2, FOREGROUND_INTENSITY = 8, FOREGROUND_RED = 4, F_DUPFD = 0, F_DUPFD_CLOEXEC = 1030, F_GETFD = 1, F_GETFL = 3, F_GETLK = 5, F_GETPATH = -1, F_OK = 0, F_RDLCK = 0, F_SETFD = 2, F_SETFL = 4, F_SETLK = 6, F_SETLKW = 7, F_UNLCK = 2, F_WRLCK = 1, GLOB_ABORTED = -2, GLOB_ALTDIRFUNC = 64, GLOB_APPEND = 1, GLOB_BRACE = 128, GLOB_DOOFFS = 2, GLOB_ERR = 4, GLOB_MAGCHAR = 256, GLOB_MARK = 8, GLOB_NOCHECK = 16, GLOB_NOESCAPE = 4096, GLOB_NOMAGIC = 512, GLOB_NOMATCH = -3, GLOB_NOSORT = 32, GLOB_NOSPACE = -1, GLOB_NOSYS = -4, GLOB_QUOTE = 1024, GLOB_TILDE = 2048, IN_ACCESS = 1, IN_ALL_EVENTS = 4095, IN_ATTRIB = 4, IN_CLOEXEC = 524288, IN_CLOSE = 24, IN_CLOSE_NOWRITE = 16, IN_CLOSE_WRITE = 8, IN_CREATE = 256, IN_DELETE = 512, IN_DELETE_SELF = 1024, IN_DONT_FOLLOW = 33554432, IN_EXCL_UNLINK = 67108864, IN_IGNORED = 32768, IN_ISDIR = 1073741824, IN_MASK_ADD = 536870912, IN_MODIFY = 2, IN_MOVE = 192, IN_MOVED_FROM = 64, IN_MOVED_TO = 128, IN_MOVE_SELF = 2048, IN_NONBLOCK = 2048, IN_ONESHOT = -2147483648, IN_ONLYDIR = 16777216, IN_OPEN = 32, IN_Q_OVERFLOW = 16384, IN_UNMOUNT = 8192, JS_EVAL_FLAG_BACKTRACE_BARRIER = 64, JS_EVAL_FLAG_COMPILE_ONLY = 32, JS_EVAL_FLAG_MASK = 232, JS_EVAL_FLAG_STRICT = 8, JS_EVAL_IS_MAIN = 4, JS_EVAL_TYPE_DIRECT = 2, JS_EVAL_TYPE_GLOBAL = 0, JS_EVAL_TYPE_INDIRECT = 3, JS_EVAL_TYPE_MASK = 3, JS_EVAL_TYPE_MODULE = 1, JS_PROMISE_FULFILLED = 1, JS_PROMISE_PENDING = 0, JS_PROMISE_REJECTED = 2, O_APPEND = 1024, O_CLOEXEC = 524288, O_CREAT = 64, O_DIRECT = 16384, O_DSYNC = 4096, O_EXCL = 128, O_NOATIME = 262144, O_NOCTTY = 256, O_NONBLOCK = 2048, O_RDONLY = 0, O_RDWR = 2, O_SYNC = 1052672, O_TRUNC = 512, O_WRONLY = 1, RWF_APPEND = 16, RWF_DSYNC = 2, RWF_HIPRI = 1, RWF_NOWAIT = 8, RWF_SYNC = 4, R_OK = 4, SIGABRT = 6, SIGALRM = 14, SIGBUS = 7, SIGCHLD = 17, SIGCONT = 18, SIGFPE = 8, SIGHUP = 1, SIGILL = 4, SIGINT = 2, SIGIO = 29, SIGKILL = 9, SIGPIPE = 13, SIGPOLL = 29, SIGPROF = 27, SIGPWR = 30, SIGQUIT = 3, SIGSEGV = 11, SIGSTKFLT = 16, SIGSTOP = 19, SIGSYS = 31, SIGTERM = 15, SIGTRAP = 5, SIGTSTP = 20, SIGTTIN = 21, SIGTTOU = 22, SIGURG = 23, SIGUSR1 = 10, SIGUSR2 = 12, SIGVTALRM = 26, SIGWINCH = 28, SIGXCPU = 24, SIGXFSZ = 25, TIOCCBRK = 21544, TIOCGPGRP = 21519, TIOCGWINSZ = 21523, TIOCINQ = 21531, TIOCLINUX = 21532, TIOCMBIC = 21527, TIOCMBIS = 21526, TIOCMGET = 21525, TIOCMSET = 21528, TIOCPKT = 21536, TIOCSBRK = 21543, TIOCSCTTY = 21518, TIOCSPGRP = 21520, TIOCSWINSZ = 21524, WRDE_BADCHAR = 2, WRDE_BADVAL = 3, WRDE_CMDSUB = 4, WRDE_NOCMD = 4, WRDE_NOSPACE = 1, WRDE_SHOWERR = 16, WRDE_SYNTAX = 5, WRDE_UNDEF = 32, W_OK = 2, X_OK = 1, inotify_event_size = 16, inspectSymbol
AsyncGeneratorFunction
class, constructible
- properties:
prototype,[Symbol.toStringTag]
AsyncGeneratorPrototype
object
- static methods:
next(),return(),throw()
Generator
class
- properties:
GeneratorFunction
class, constructible
- properties:
prototype,[Symbol.toStringTag]
GeneratorPrototype
object
- static methods:
next(),return(),throw()
MapIterator
class, constructible
- static methods:
concat(),from() - methods:
drop(),every(),filter(),find(),flatMap(),forEach(),map(),reduce(),some(),take(),toArray(),[Symbol.iterator]() - properties:
[Symbol.toStringTag] (get/set)
SetIterator
class, constructible
- static methods:
concat(),from() - methods:
drop(),every(),filter(),find(),flatMap(),forEach(),map(),reduce(),some(),take(),toArray(),[Symbol.iterator]() - properties:
[Symbol.toStringTag] (get/set)
TypeIds
object
- static values:
array = 4,float64 = 0,int = 5,nan = 1,object = 3,undefined = 1
TypedArray
class, constructible
- static methods:
from(),of() - methods:
at(),copyWithin(),entries(),every(),fill(),filter(),find(),findIndex(),findLast(),findLastIndex(),forEach(),includes(),indexOf(),join(),keys(),lastIndexOf(),map(),reduce(),reduceRight(),reverse(),set(),slice(),some(),sort(),subarray(),toLocaleString(),toReversed(),toSorted(),toString(),values(),with(),[Symbol.iterator]() - properties:
buffer (get),byteLength (get),byteOffset (get),length (get),[Symbol.toStringTag] (get)
ansiStyles
object
- static methods:
ansi256ToAnsi(),hexToAnsi(),hexToAnsi256(),hexToRgb(),rgbToAnsi(),rgbToAnsi256() - static values:
bgBlack,bgBlackBright,bgBlue,bgBlueBright,bgColor,bgCyan,bgCyanBright,bgGray,bgGreen,bgGreenBright,bgGrey,bgMagenta,bgMagentaBright,bgRed,bgRedBright,bgWhite,bgWhiteBright,bgYellow,bgYellowBright,black,blackBright,blue,blueBright,bold,codes,color,cyan,cyanBright,dim,gray,green,greenBright,grey,hidden,inverse,italic,magenta,magentaBright,modifier,overline,red,redBright,reset,strikethrough,underline,white,whiteBright,yellow,yellowBright
default
object
- static methods:
MIMEParams(),MIMEType(),TextDecoder(),TextEncoder(),_errnoException(),_exceptionWithHostPort(),_extend(),aborted(),callbackify(),convertProcessSignalToExitCode(),debounce(),debug(),debuglog(),deprecate(),diff(),format(),formatWithOptions(),getCallSite(),getCallSites(),getSystemErrorMap(),getSystemErrorMessage(),getSystemErrorName(),inherits(),inspect(),isArray(),isBoolean(),isBuffer(),isDate(),isDeepStrictEqual(),isError(),isFunction(),isNull(),isNullOrUndefined(),isNumber(),isObject(),isPartialDeepStrictEqual(),isPrimitive(),isRegExp(),isString(),isSymbol(),isUndefined(),log(),markPromiseAsHandled(),parseArgs(),parseEnv(),promisify(),setTraceSigInt(),stripVTControlCharacters(),styleText(),throttle(),toUSVString(),transferableAbortController(),transferableAbortSignal() - static values:
inspectColors,inspectCustom,types
errors
object
- static values:
'0','1','10','100','101','102','103','104','105','106','107','108','109','11','110','111','112','113','114','115','116','117','118','119','12','120','121','122','123','124','125','126','127','128','129','13','130','131','132','14','15','16','17','18','19','2','20','21','22','23','24','25','26','27','28','29','3','30','31','32','33','34','35','36','37','38','39','4','40','41','42','43','44','45','46','47','48','49','5','50','51','52','53','54','55','56','57','58','59','6','60','61','62','63','64','65','66','67','68','69','7','70','71','72','73','74','75','76','77','78','79','8','80','81','82','83','84','85','86','87','88','89','9','90','91','92','93','94','95','96','97','98','99',length = 133
types
object
- static methods:
isAnyArrayBuffer(),isArgumentsObject(),isArrayBuffer(),isArrayBufferView(),isArrayLike(),isAsyncFunction(),isAsyncGenerator(),isAsyncGeneratorFunction(),isAsyncIterable(),isBigInt64Array(),isBigIntObject(),isBigUint64Array(),isBooleanObject(),isBoxedPrimitive(),isConstructor(),isDataView(),isDate(),isFloat32Array(),isFloat64Array(),isGenerator(),isGeneratorFunction(),isGeneratorObject(),isInt16Array(),isInt32Array(),isInt8Array(),isIterable(),isIterator(),isMap(),isMapIterator(),isModuleNamespaceObject(),isNativeError(),isNumberObject(),isPromise(),isProxy(),isRegExp(),isSet(),isSetIterator(),isSharedArrayBuffer(),isStringObject(),isSymbolObject(),isTypedArray(),isUint16Array(),isUint32Array(),isUint8Array(),isUint8ClampedArray(),isWeakMap(),isWeakSet()