Utility methods for the hapi ecosystem. This module is not intended to solve every problem for everyone, but rather as a central place to store hapi-specific methods. If you're looking for a general purpose utility module, check out lodash or underscore.
Lead Maintainer: Nathan LaFreniere
Table of Contents
Introduction
The Hoek library contains some common functions used within the hapi ecosystem. It comes with useful methods for Arrays (clone, merge, applyToDefaults), Objects (removeKeys, copy), Asserting and more.
For example, to use Hoek to set configuration with default options:
Under each of the sections (such as Array), there are subsections which correspond to Hoek methods. Each subsection will explain how to use the corresponding method. In each js excerpt below, the var Hoek = require('hoek');
is omitted for brevity.
Object
Hoek provides several helpful methods for objects and arrays.
clone(obj)
This method is used to clone an object or an array. A deep copy is made (duplicates everything, including values that are objects, as well as non-enumerable properties).
cloneWithShallow(obj, keys)
keys is an array of key names to shallow copy
This method is also used to clone an object or array, however any keys listed in the keys
array are shallow copied while those not listed are deep copied.
merge(target, source, isNullOverride, isMergeArrays)
isNullOverride, isMergeArrays default to true
Merge all the properties of source into target, source wins in conflict, and by default null and undefined from source are applied. Merge is destructive where the target is modified. For non destructive merge, use applyToDefaults
.
applyToDefaults(defaults, options, isNullOverride)
isNullOverride defaults to false
Apply options to a copy of the defaults
Apply options with a null value to a copy of the defaults
applyToDefaultsWithShallow(defaults, options, keys)
keys is an array of key names to shallow copy
Apply options to a copy of the defaults. Keys specified in the last parameter are shallow copied from options instead of merged.
deepEqual(b, a, [options])
Performs a deep comparison of the two values including support for circular dependencies, prototype, and properties. To skip prototype comparisons, use options.prototype = false
unique(array, key)
Remove duplicate items from Array
mapToObject(array, key)
Convert an Array into an Object
intersect(array1, array2)
Find the common unique items in two arrays
contain(ref, values, [options])
Tests if the reference value contains the provided values where:
ref
- the reference string, array, or object.values
- a single or array of values to find within theref
value. Ifref
is an object,values
can be a key name, an array of key names, or an object with key-value pairs to compare.options
- an optional object with the following optional settings:deep
- iftrue
, performed a deep comparison of the values.once
- iftrue
, allows only one occurrence of each value.only
- iftrue
, does not allow values not explicitly listed.part
- iftrue
, allows partial match of the values (at least one must always match).
Note: comparing a string to overlapping values will result in failed comparison (e.g. contain('abc', ['ab', 'bc'])
). Also, if an object key's value does not match the provided value, false
is returned even when part
is specified.
flatten(array, [target])
Flatten an array
reach(obj, chain, [options])
Converts an object key chain string to reference
options
- optional settingsseparator
- string to split chain path on, defaults to '.'default
- value to return if the path or value is not present, default isundefined
strict
- iftrue
, will throw an error on missing member, default isfalse
functions
- iftrue
allow traversing functions for properties.false
will throw an error if a function is part of the chain.
A chain including negative numbers will work like negative indices on an array.
reachTemplate(obj, template, [options])
Replaces string parameters ({name}
) with their corresponding object key values by applying the (reach()
)[#reachobj-chain-options] method where:
obj
- the context object used for key lookup.template
- a string containing{}
parameters.options
- optional (reach()
)[#reachobj-chain-options] options.
transform(obj, transform, [options])
Transforms an existing object into a new one based on the supplied obj
and transform
map. options
are the same as the reach
options.
shallow(obj)
Performs a shallow copy by copying the references of all the top level children where:
obj
- the object to be copied.
stringify(obj)
Converts an object to string using the built-in JSON.stringify()
method with the difference that any errors are caught and reported back in the form of the returned string. Used as a shortcut for displaying information to the console (e.g. in error message) without the need to worry about invalid conversion.
Timer
A Timer object. Initializing a new timer object sets the ts to the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.
Bench
Same as Timer with the exception that ts
stores the internal node clock which is not related to Date.now()
and cannot be used to display human-readable timestamps. More accurate for benchmarking or internal timers.
Binary Encoding/Decoding
base64urlEncode(value)
Encodes value in Base64 or URL encoding
base64urlDecode(value)
Decodes data in Base64 or URL encoding.
Escaping Characters
Hoek provides convenient methods for escaping html characters. The escaped characters are as followed:
escapeHtml(string)
escapeHeaderAttribute(attribute)
Escape attribute value for use in HTTP header
escapeRegex(string)
Escape string for Regex construction
Errors
assert(condition, message)
Note that you may also pass an already created Error object as the second parameter, and assert
will throw that object.
abort(message)
First checks if process.env.NODE_ENV === 'test'
, and if so, throws error message. Otherwise, displays most recent stack and then exits process.
displayStack(slice)
Displays the trace stack
callStack(slice)
Returns a trace stack array.
Function
nextTick(fn)
Returns a new function that wraps fn
in process.nextTick
.
once(fn)
Returns a new function that can be run multiple times, but makes sure fn
is only run once.
ignore
A simple no-op function. It does nothing at all.
Miscellaneous
uniqueFilename(path, extension)
path
to prepend with the randomly generated file name. extension
is the optional file extension, defaults to ''
.
Returns a randomly generated file name at the specified path
. The result is a fully resolved path to a file.
isInteger(value)
Check value
to see if it is an integer. Returns true/false.