lib

module:lib

Description:
  • General purpose utilities

Source:

Type Definitions

ParamsOptions

Description:
  • An object to be used with toParams for validation

Source:
Properties:
Name Type Attributes Description
name boolean

to save a value with different name than in the original query

type string <optional>

convert the input to the type format, default text Supported types:

  • string types: string, text,
  • boolean types: bool, boolean,
  • numeric types: int, bigint, long, number, float, real, double, counter, clock, now, random
  • object types: list, map, obj, object, array, json,
  • date/time types: mtime, date, time, timestamp, datetime
  • special types: set, email, symbol, url, phone, e164, regexp
dflt boolean <optional>

use this value if property does not exists or undefined

dfltempty boolean <optional>

also use the dflt value for empty properties

required boolean <optional>

if true the target value must not be empty, the check is performed after type conversion, if an object it checks the target object using lib.isMatched at the end

errmsg boolean <optional>

return this error on error or invalid format or required condition, it may contain %s sprintf-like placeholders depending on the error

min boolean <optional>

minimum length for the target data, returns an error if smaller, for list type will skip item from the list

max boolean <optional>

maximum length alowed, returns an error if longer

trunc boolean <optional>

if true and longer than max just truncate the value instead of returning an error or skipping

separator boolean <optional>

for list type default separator is ,|, for map type default is :;

delimiter boolean <optional>

map type contains elements separated by , by default, use another if commas are expected

regexp boolean <optional>

validate input against this regexp and return an error if not matched, for list type skip items not matched

noregexp boolean <optional>

validate the input against this regexp and return an error if matched, for list type skip items matched

datatype boolean <optional>

convert each value or item into this type, used by string/list types

maptype boolean <optional>

for maps convert each value to this type

novalue boolean <optional>

if the target value equals then ignore the parameter, can be a list of values to be ignored or an object { name, value }. For lists this is a number of items in the list, if less or equal the list is ignored or reset.

ignore boolean <optional>

if true skip this parameter

optional boolean <optional>

for date types, if true do not assign the current time for empty values

value boolean <optional>

assign this value unconditionally

values boolean <optional>

a list of allowed values, if not present the parameter is ignored

values_map boolean <optional>

an object map for values, replace matching values with a new one

params boolean <optional>

an object with schema to validate for json/obj/array types

empty boolean <optional>

if true and the target value is empty return as empty, by default empty values are ignored

setempty boolean <optional>

to be used with empty, instead of skipping set with this value at the end

keepempty boolean <optional>

for list type keep empty items in the list, default is skip empty items

minlist boolean <optional>

min allowed length of the target array for list/map types, returns error if less

maxlist boolean <optional>

max allowed length of the target array for list/map types, returns error if longer

minnum boolean <optional>

min allowed number after convertion by toNumber, for numbers and mtime

maxnum boolean <optional>

max allowed number after convertion by toNumber, for numbers and mtime

mindate boolean <optional>

min allowed date after convertion by toDate, can be a Date or number

maxdate boolean <optional>

max allowed date after convertion by toDate, can be a Date or number

label boolean <optional>

alternative name to use in error messages which uses sprintf-like placeholders, all min/max like errors have name as first and threshold as second arg, label can be set to use friendlier name

strip boolean <optional>

a regexp with characters to strip from the final value

upper/lower boolean <optional>

transform case

cap boolean <optional>

capitalize the value

trim boolean <optional>

trim the final value if a string

replace boolean <optional>

an object map with characters to be replaced with other values

base64 boolean <optional>

decode from base64

Type:
  • object

Members

(static) base32 :regexp

Description:
  • base32 characters

Source:

(static) base36 :regexp

Description:
  • base36 characters

Source:

(static) base62 :regexp

Description:
  • base62 characters

Source:

(static) base64 :regexp

Description:
  • base64 characters

Source:

(static) empty :object

Description:
  • empty object, frozen

Source:

(static) emptylist :array

Description:
  • empty array, frozen

Source:

(static) noop :function

Description:
  • empty function to be used when callback was no provided

Source:

(static) rxAscii :regexp

Description:
  • ascii chars validation

Source:

(static) rxCamel :regexp

Description:
  • characters for camelizing

Source:

(static) rxDateType :regexp

Description:
  • date and time column types

Source:

(static) rxDigits :regexp

Description:
  • digits only

Source:

(static) rxEmail :regexp

Description:
  • email validation

Source:

(static) rxEmpty :regexp

Description:
  • empty or spaces only

Source:

(static) rxFloat :regexp

Description:
  • float number validation

Source:

(static) rxHtml :regexp

Description:
  • html brackets

Source:

(static) rxIpaddress :regexp

Description:
  • IP address validation

Source:

(static) rxListType :regexp

Description:
  • list and sets column types

Source:

(static) rxNoDigits :regexp

Description:
  • no digits

Source:

(static) rxNoHtml :regexp

Description:
  • exclude html brackets

Source:

(static) rxNoSpecial :regexp

Description:
  • excclude punctuation and other special characters

Source:

(static) rxNoXss :regexp

Description:
  • exclude XSS characters

Source:

(static) rxNumber :regexp

Description:
  • number validation

Source:

(static) rxNumericType :regexp

Description:
  • numeric column types

Source:

(static) rxObjectType :regexp

Description:
  • object column types

Source:

(static) rxPhone :regexp

Description:
  • phonre validation

Source:

(static) rxSpecial :regexp

Description:
  • punctuation and other special characters

Source:

(static) rxSplit :regexp

Description:
  • list split characters

Source:

(static) rxSymbol :regexp

Description:
  • symbol name validation

Source:

(static) rxTrue :regexp

Description:
  • true validation

Source:

(static) rxUrl :regexp

Description:
  • url validation

Source:

(static) rxUuid :regexp

Description:
  • uuid validation

Source:

(static) rxVersion :regexp

Description:
  • version validation

Source:

(static) rxXss :regexp

Description:
  • XSS characters

Source:

(static) uriSafe :string

Description:
  • characters allowed in urls

Source:

(static) wordBoundaries :string

Description:
  • word boundaries characters

Source:

Methods

(static) AhoCorasick()

Description:
  • Text search using Aho-Corasick algorithm, based on https://github.com/BrunoRB/ahocorasick

Source:

(static) __(msg, …argsopt) → {string}

Description:
  • Simple i18n translation method compatible with other popular modules, supports the following usage:

Source:
Parameters:
Name Type Attributes Description
msg string
args any <optional>
<repeatable>
Returns:
Type Description
string
Example
lib.__(name)
lib.__(fmt, arg,...)
lib.__({ phrase: "", locale: "" }, arg...

(async, static) aexecProcess(cmd, optionsopt) → {object}

Description:
Source:
Parameters:
Name Type Attributes Description
cmd string
options object <optional>
Returns:
Type Description
object

in format { stdout, stderr, err }

Example
const { stdout } = lib.aexecProcess("ls -ls")

(async, static) afetch(uri, optionsopt) → {object}

Description:
Source:
Parameters:
Name Type Attributes Description
uri string

can be full URL or an object with parts of the url, same format as in url.format

options object | FetchOptions <optional>

customize request

Returns:
Type Description
object
  • result as an object { err, data, obj, req } where data/obj are properties fro the req for convenience
Example
const { err, data } = await lib.afetch("http://api.host.com/file.txt");
const { err, obj } = await lib.afetch("http://api.host.com/user/123");
const { err, obj } = await lib.afetch({ url: "http://api.host.com/user/123", query: { t: 1 } });
const { err, obj } = await lib.afetch({ url: "http://api.host.com/user/123", postdata: { name: "myname" } });
const { err, obj } = await lib.afetch({ url: "http://api.host.com/user/123", method: "PUT", body: { name: "myname" } });

(async, static) afindProcess(optionsopt) → {object}

Description:
Source:
Parameters:
Name Type Attributes Description
options object <optional>
Returns:
Type Description
object

in format { data, err }

Example
const { data } = await lib.afindProcess({ filter: "bkjs" });
console.log(data)
[
 { pid: 65841, cmd: 'bkjs: watcher' },
 { pid: 65867, cmd: 'bkjs: master' },
 { pid: 65868, cmd: 'bkjs: worker' },
 { pid: 65869, cmd: 'bkjs: web' }
]

(async, static) areadFile(file, optionsopt) → {object}

Description:
Source:
Parameters:
Name Type Attributes Description
file string
options object <optional>
Returns:
Type Description
object

in format { data, err }

(async, static) areadFile(cmds, optionsopt) → {object}

Description:
Source:
Parameters:
Name Type Attributes Description
cmds object
options object <optional>
Returns:
Type Description
object

in format { stdout, stderr, err }

Example
const { stdout, stderr } = await lib.aspawnSeries({"ls": "-l", "ps": "agx" }, { stdio:"pipe" })

(static) arrayEqual(list1, list2)

Description:
  • Returns true if both arrays contain same items, only primitive types are supported

Source:
Parameters:
Name Type Description
list1 Array.<any>
list2 Array.<any>

(static) arrayFlatten(list)

Description:
  • Flatten array of arrays into a single array

Source:
Parameters:
Name Type Description
list Array.<any>

(static) arrayLength(list) → {int}

Description:
  • Return the length of an array or 0 if it is not an array

Source:
Parameters:
Name Type Description
list Array.<any>
Returns:
Type Description
int

(static) arrayRemove(list, item) → {Array.<any>}

Description:
  • Remove the given item from the list in place, returns the same list

Source:
Parameters:
Name Type Description
list Array.<any>
item any
Returns:
Type Description
Array.<any>

(static) arrayUnique(list, key)

Description:
  • Returns only unique items in the array, optional key specified the name of the column to use when determining uniqueness if items are objects.

Source:
Parameters:
Name Type Description
list Array.<any>
key string

(async, static) aspawnProcess(cmd, optionsopt) → {object}

Description:
Source:
Parameters:
Name Type Attributes Description
cmd string
options object <optional>
Returns:
Type Description
object

in format { proc, err }

(static) autoType(val) → {string}

Description:
  • Detect type from the value

Source:
Parameters:
Name Type Description
val any
Returns:
Type Description
string

detected library type name

(static) base64ToJson(data, secret, optionsopt) → {object}

Description:
  • Parse base64 JSON into JavaScript object, in some cases this can be just a number then it is passed as it is, if secret is given verify that data is not changed and was signed with the same secret

Source:
Parameters:
Name Type Attributes Description
data any
secret string
options object <optional>
Returns:
Type Description
object

(static) call(obj, methodopt, …argsopt) → {any}

Description:
  • Call a function safely with context:

Source:
Parameters:
Name Type Attributes Description
obj function | object

a function to try or an object with a method

method string <optional>

if obj is an object try to call the method by name

args any <optional>
<repeatable>

pass the rest arguments to the function

Returns:
Type Description
any

the function result

Example
lib.call(func,..)
lib.call(context, func, ...)
lib.call(context, method, ...)

(static) cidrRange()

Description:
  • Return first and last IP addresses for the CIDR block

Source:

(static) clock() → {int}

Description:
  • Returns current time in microseconds since January 1, 1970, UTC

Source:
Returns:
Type Description
int

(static) configParse(data, optionsopt) → {Array.<string>}

Description:
  • Parse data as config format name=value per line

    Include supports:

    • The format is: $include filename the contents of the given file will be included in place and parsed. File name may contain placeholders formatted as @name@ where name can refer to any property inside the options or inside the modules as @module.name@

    Supports sections:

    • The format is: [name=value,...] or [name!=value,...] where name is a property name with optional value(s).
    • if the value is empty then it just checks if the property is empty.
    • != denotes negative condition, i.e. not matching or NOT empty
    • section names may refer deep into objects like aws.region or instance.tag, all modules will be checked inside options.modules object only, all other names are checked in the top level options.

    Sections work like a filter, only if a property matches it is used otherwise skipped completely, it uses lib.isTrue for matching so checking an item in an array will work as well. The [global] section can appear anytime to return to global mode

Source:
Parameters:
Name Type Attributes Description
data string | Array.<string>

a string or array with config lines, a string will be split by newline

options object <optional>

options with context

Properties
Name Type Attributes Description
modules object <optional>

an object with modules to use for section conditions, in most cases it is {$link module:modules}

obj boolean <optional>

return as an object by { key1: value, key2: value }

list boolean <optional>

return as an array of [key1, value]

Returns:
Type Description
Array.<string>

an array of config keys and values as [-key1, val1, -key2, val2,...]

(static) copyFile(src, dst, overwriteopt, callbackopt)

Description:
  • Copy file, overwrite is optional flag, by default do not overwrite

Source:
Parameters:
Name Type Attributes Description
src string
dst string
overwrite boolean <optional>

true to overwrite

callback function <optional>

(static) cpuStats() → {object}

Description:
  • Return CPU process stats in an object

Source:
Returns:
Type Description
object

(static) daysInMonth(year, month) → {int}

Description:
  • Return the number of days in the given month of the specified year.

Source:
Parameters:
Name Type Description
year int
month int
Returns:
Type Description
int

(static) decodeURIComponent(str) → {string}

Description:
  • No-exception version of the global function, on error return empty string

Source:
Parameters:
Name Type Description
str string
Returns:
Type Description
string

(static) decrypt(key, data, optionsopt) → {string}

Description:
  • Decrypt data with the given key, GCM mode is default

Source:
Parameters:
Name Type Attributes Description
key string | Buffer
data string | Buffer
options object <optional>
Returns:
Type Description
string

(static) deferCallback(parent, msg, callback, timeoutopt) → {object}

Description:
  • Register the callback to be run later for the given message, the message may have the __deferId property which will be used for keeping track of the responses or it will be generated. A timeout is created for this message, if runCallback for this message will not be called in time the timeout handler will call the callback anyway with the original message.

Source:
Parameters:
Name Type Attributes Description
parent object

can be any object and is used to register the timer and keep reference to it, a _defer object will be created inside the parent.

msg object

the message

callback function

will be called with only one argument which is the message itself, what is inside the message this function does not care. If any errors must be passed, use the message object for it, no other arguments are expected.

timeout int <optional>

how long to wait, if not given lib.deferTimeout is used

Returns:
Type Description
object

an object with timer and callback

(static) deferInterval()

Description:
  • Assign or clear an interval timer by name, keep the reference in the given parent object

Source:

(static) deferShutdown()

Description:
  • Clear all pending timers

Source:

(static) doWhilst(iterator, test, callbackopt, directopt)

Description:
  • Keep running iterator while the test function returns true, call the callback at the end if specified. All functions are called via setImmediate unless the direct argument is true

Source:
Parameters:
Name Type Attributes Description
iterator function
test function
callback function <optional>
direct boolean <optional>
Example
var count = 0;
lib.doWhilst(
   (next, data) => {
       count++;
       setTimeout(next, 1000);
   },
   (data) => (count < 5),
   (err, data) => {
        console.log(err, data, count);
   });

(static) domainName(host, toplevelopt) → {string}

Description:
  • Extract domain from the host name, takes all host parts except the first one, if toplevel is true return 2 levels only

Source:
Parameters:
Name Type Attributes Description
host string
toplevel boolean <optional>
Returns:
Type Description
string

(static) dropPrivileges()

Description:
  • Drop root privileges and switch to a regular user

Source:

(static) encodeURIComponent(str) → {string}

Description:
  • Encode with additional symbols, convert these into percent encoded: ! -> %21, * -> %2A, ' -> %27, ( -> %28, ) -> %29

Source:
Parameters:
Name Type Description
str string
Returns:
Type Description
string

(static) encrypt(key, data, optionsopt) → {string|Buffer}

Description:
  • Encrypt data with the given key, GCM mode is default

Source:
Parameters:
Name Type Attributes Description
key string | Buffer
data string | Buffer
options object <optional>
Returns:
Type Description
string | Buffer

(static) entityToText(str) → {string}

Description:
  • Convert html entities into their original symbols

Source:
Parameters:
Name Type Description
str string
Returns:
Type Description
string

(static) escapeUnicode(str) → {string}

Description:
  • Convert all Unicode binary symbols into Javascript text representation

Source:
Parameters:
Name Type Description
str string
Returns:
Type Description
string

(static) everyParallel(tasks, callbackopt, directopt)

Description:
Source:
Parameters:
Name Type Attributes Description
tasks Array.<function()>
callback function <optional>
direct boolean <optional>

(static) everySeries(tasks, callbackopt, directopt)

Description:
  • Same as module:lib.series but all functions will be called with errors passed to the next task, only the last passed error will be returned

Source:
Parameters:
Name Type Attributes Description
tasks Array.<function()>
callback function <optional>
direct boolean <optional>
Example
lib.everySeries([
   function(next) {
      next("error1", "data1");
   },
   function(next, err, data) {
      setTimeout(function () { next(err, "data2"); }, 100);
   },
], (err, data) => {
    console.log(err, data);
});

(static) execProcess(cmd, optionsopt, callbackopt)

Description:
  • Run the process and return all output to the callback, this a simple wrapper around child_processes.exec so the lib.runProcess can be used without importing the child_processes module. All fatal errors are logged.

Source:
Parameters:
Name Type Attributes Description
cmd string
options object <optional>
  • options.merge if set append stdout to stderr and return combined single value separated by 2 newlines
callback function <optional>

(err, stdout, stderr)

Example
lib.execProcess("ls -ls", lib.log)

(static) fetch(uri, optionsopt, callbackopt)

Description:
  • Make requests using HTTP(S) and pass it to the callback if provided

Source:
Parameters:
Name Type Attributes Description
uri string | object

can be full URL or an object with property url:

options object | FetchOptions <optional>

customize request with options, see module:lib.FetchOptions

callback function <optional>

callback as (err, request) where request is {FetchOptions} object combined with input options and updated fields

Examples
lib.fetch("http://api.host.com/user/123", (err, req) => {
   if (req.status == 200) console.log(req.obj);
});

get a file if not downloaded already

var file = "/tmp/logo.png";
lib.fetch("https://bucket.s2.amazonaws.com/logo.png", { file, conditional: 1 }, (err, req) => {
    if (req.status >= 200) ...
});

post JSON with authorization

var data = {
   postdata: { ... },
   headers: { Authorization: "Bearer " + jwt },
   retryCount: 3
};
lib.fetch("https://some.api.com/endpoint", data, (err, req) => {
    console.log(req.status, req.obj);
});

(static) findFile()

Description:
Source:

(static) findFileFilter()

Description:
  • Filter function to be used in findFile methods

Source:

(static) findFileSync(dir, optionsopt) → {Array.<string>|Array.<object>}

Description:
  • Return list of files than match filter recursively starting with given path, dir is the starting path.

Source:
Parameters:
Name Type Attributes Description
dir string
options object <optional>
  • include - a regexp with file pattern to include
    • exclude - a regexp with file pattern to exclude
    • filter - a function(file, stat) that return 1 if the given file matches, stat is a object returned by fs.statSync
    • depth - if a number it specifies max depth to go into the subfolders, starts with 1
    • types - a string with types of files to include: d - a dir, f - a file, l - a symlink, c - char dev, b - block dev, s - socket, p - a FIFO
    • base - if set only keep base file name in the result, not full path
    • details - return the whole stat structure instead of just names
Returns:
Type Description
Array.<string> | Array.<object>
Example
lib.findFileSync("modules/", { depth: 1, types: "f", include: /\.js$/ }).sort()

(static) findProcess(options, callback)

Description:
  • Return a list of processes

Source:
Parameters:
Name Type Description
options object
Properties
Name Type Attributes Description
filter regexp <optional>

return only matching

callback function

in format (err, list) where list is { pid, cmd }

(static) findWords()

Description:
  • Return an array of words`` found in the given text`` separated by delimiters, this a brute force search for every keyword and using lib.isWord to detect boundaries. This is an alternative to AhoCorasick if number of words is less than 50-70.

Source:

(static) forEach(list, iterator, callback, direct)

Description:
  • Apply an iterator function to each item in an array in parallel. Execute a callback when all items have been completed or immediately if there is an error provided.

Source:
Parameters:
Name Type Description
list Array.<any>
iterator function
callback function
direct boolean

controls how the final callback is called, if true it is called directly otherwisde via setImmediate

Example
lib.forEach([ 1, 2, 3 ], function (i, next) {
  console.log(i);
  next();
}, (err) => {
  console.log('done');
});

(static) forEachItem(options, next, iterator, callbackopt, directopt)

Description:
  • Apply an iterator function to each item returned by the next(item, cb) function until it returns null or the iterator returns an error in the callback, the final callback will be called after all iterators are finished.

    If no item is available the next() should return empty value, it will be called again in options.interval ms if specified or immediately in the next tick cycle.

    The max number of iterators to run at the same time is controlled by options.max, default is 1.

    The maximum time waiting for items can be specified by options.timeout, it is not an error condition, just another way to stop processing if it takes too long because the next() function is a black box just returning items to process. Timeout will send null to the queue and it will stop after all iterators are finished.

Source:
Parameters:
Name Type Attributes Description
options object
next function
iterator function
callback function <optional>
direct boolean <optional>
Example
var list = [1, 2, "", "", 3, "", 4, "", "", "", null];
lib.forEachItem({ max: 2, interval: 1000, timeout: 30000 },
    function(next) {
        next(list.shift());
    },
    function(item, next) {
        console.log("item:", item);
    next();
}, (err) => {
   console.log("done", err);
});

(static) forEachLimit(list, limit, iterator, callbackopt, directopt)

Description:
  • Apply an iterator function to each item in an array in parallel as many as specified in limit at a time. Execute a callback when all items have been completed or immediately if there is is an error provided.

Source:
Parameters:
Name Type Attributes Default Description
list Array.<any>
limit int 1
iterator function
callback function <optional>
direct boolean <optional>

(static) forEachLine(file, options, lineCallback, endCallbackopt)

Description:
  • Call callback for each line in the file options may specify the following parameters:

Source:
Parameters:
Name Type Attributes Description
file string
options object
  • sync - read file synchronously and call callback for every line
  • abort - signal to stop processing
  • limit - number of lines to process and exit
  • length - amount of data in bytes to process and exit
  • count - accumulate up to this number of lines in an array before sending a batch for processing
  • batchsize - accumulate up to this size before sending a batch for processing
  • skip - number of lines to skip from the start
  • progress - if > 0 report how many lines processed so far every specified lines
  • until - skip lines until this regexp matches
  • ignore - skip lines that match this regexp
  • header - if true then skip first line because it is the a header, if options.header it is a function it will be called with the first line as an argument and must return true if this line needs to be skipped
  • json - each line represents an JSON object, convert and pass it to the line callback if not null
  • split - split every line before calling the callback, it uses phraseSplit
  • keepempty - by default is enabled if split is set to keep empty fields in the line array
  • separator - a string with characters to be used for splitting, default is ,
  • rxLine - a Regexp for line splitting, default is lib.rxLine
  • quotes - a string with characters to be used for phrase splitting, default is "'
  • quiet - do not report about open file errors
  • direct - to pass to lib.forEachLimit for true async processing
  • concurrency - how many lines to process at the same time
  • buflength - size of the internal buffer, 4096 default
  • tail - if > 0 async version will keep trying to read from file after this number of ms

Properties updated and returned in the options:

  • nlines - number of lines read from the file
  • nbytes - amount of data passed to line callback
  • ncalls - number of lines/batches passed to the line callback
  • npos - current position in the file
  • nskip - number of lines skipped
lineCallback function
endCallback function <optional>
Example
lib.forEachLine("file.csv" , { split: 1 }, (line, next) => {
    console.log(line[0], line[1]);
}, lib.log)

(static) forEachLineSync()

Description:
  • Sync version of the module:lib.forEachLine, read every line and call callback which may not do any async operations because they will not be executed right away but only after all lines processed

Source:

(static) forEachSeries(list, iterator, callbackopt, directopt)

Description:
  • Apply an iterator function to each item in an array serially. Execute a callback when all items have been completed or immediately if there is is an error provided.

Source:
Parameters:
Name Type Attributes Description
list Array.<any>
iterator function
callback function <optional>
direct boolean <optional>
Example
lib.forEachSeries([ 1, 2, 3 ], function (i, next, data) {
   console.log(i, data);
   next(null, data);
}, (err, data) => {
   console.log('done', data);
});

(static) forEvery(list, iterator, callbackopt, directopt)

Description:
  • Same as module:lib.forEach except that the iterator will be called for every item in the list, all errors will be ignored

Source:
Parameters:
Name Type Attributes Description
list Array.<any>
iterator function
callback function <optional>
direct boolean <optional>

(static) forEveryLimit(list, limit, iterator, callbackopt, directopt)

Description:
  • Same as module:lib.forEachLimit but does not stop on error, all items will be processed and errors will be collected in an array and passed to the final callback

Source:
Parameters:
Name Type Attributes Default Description
list Array.<any>
limit int 1
iterator function
callback function <optional>
direct boolean <optional>

(static) forEverySeries(list, iterator, callbackopt, directopt)

Description:
  • Same as module:lib.forEachSeries except that the iterator will be called for every item in the list, all errors will be passed to the next item with optional additional data argument.

Source:
Parameters:
Name Type Attributes Description
list Array.<any>
iterator function
callback function <optional>
direct boolean <optional>
Example
lib.forEverySeries([ 1, 2, 3 ], function (i, next, err, data) {
  console.log(i, err, data);
  next(err, i, data);
}, (err, data) => {
  console.log('done', err, data);
});

(static) fromBase32(str, optionsopt)

Description:
  • Convert a string in base32 into a Buffer

Source:
Parameters:
Name Type Attributes Description
str string

base32 encoded string

options object <optional>
Properties
Name Type Attributes Description
alphabet string <optional>

alphabet to use for decoding

(static) fromBase62(num, alphabet) → {number}

Description:
  • Convert base62 number as a string into base10 number

Source:
Parameters:
Name Type Description
num string
alphabet string
Returns:
Type Description
number

(static) fromBase64url(str, binaryopt) → {string|Buffer}

Description:
  • Decode base64url into a string

Source:
Parameters:
Name Type Attributes Description
str string
binary boolean <optional>

return as Buffer

Returns:
Type Description
string | Buffer

(static) gcStats() → {object}

Description:
  • Return GC stats if enabled is true, starts if not running, if not enabled stops the observer

Source:
Returns:
Type Description
object

(static) getArg(name, dfltopt) → {string}

Description:
  • Return commandline argument value by name

Source:
Parameters:
Name Type Attributes Description
name string

argument name

dflt any <optional>

return this value if no argument found

Returns:
Type Description
string

(static) getArgInt(name, dfltopt) → {int}

Description:
  • Return commandline argument value as a number

Source:
Parameters:
Name Type Attributes Description
name string

argument name

dflt any <optional>

return this value if no argument found

Returns:
Type Description
int

(static) getHashid(optionsopt) → {string}

Description:
  • Return cached Hashids instance for the given configuration, see https://github.com/niieani/hashids.js for docs, NOTE: only .encode and .decode methods are implemented. Properties:

Source:
Parameters:
Name Type Attributes Description
options object <optional>
Properties
Name Type Attributes Description
salt string <optional>

hashid salt, default is lib.salt

min int <optional>

minimum size of a hashid

alphabet string <optional>

chars allowed in hashids, default is lib.base32

separators string <optional>

hashid separator characters

counter int <optional>

max counter value to wrap back to 1, default is 65535

Returns:
Type Description
string

hashids instance

(static) getWorkers(filteropt, filteropt) → {Array.<object>}

Description:
  • Return a worker by id or list of workers, useful only in primary process only, always returns an object.

Source:
Parameters:
Name Type Attributes Description
filter string | number <optional>

a string or number then it is used as worker id, returns a worker or empty string.

filter object <optional>

every worker is checked against all its properties:

  • if null a property must be empty: null, "", undefined
  • if undefined then a property must not be empty
  • otherwise it must match by value
Returns:
Type Description
Array.<object>

list of worker Prociess objects

(static) getuid() → {int}

Description:
  • Return current Unix user id

Source:
Returns:
Type Description
int

(static) hash(data, algorithmopt, encodeopt) → {string}

Description:
  • Hash wrapper without exceptions for node crypto createHash

Source:
Parameters:
Name Type Attributes Description
data string | Buffer

data to hash

algorithm string <optional>

sha1 is default, any supported hash algorithm by node:crypto

encode string <optional>

encoding, base64 by default

Returns:
Type Description
string

calculated hash or empty string on error

(static) heapStats() → {object}

Source:
Returns:
Type Description
object

(static) inCidr()

Description:
  • Return true if the given IP address is within the given CIDR block

Source:

(static) int2ip()

Description:
  • Convert an integer into IP address

Source:

(static) ip2int()

Description:
  • Convert an IP address into integer

Source:

(static) isArg(name) → {boolean}

Description:
  • Returns true of given arg(s) are present in the command line, name can be a string or an array of strings.

Source:
Parameters:
Name Type Description
name string

argument name

Returns:
Type Description
boolean

(static) isArray(val, dflt) → {Array.<any>|undefined}

Source:
Parameters:
Name Type Description
val Array.<any>
dflt any
Returns:
Type Description
Array.<any> | undefined

the array if the value is non empty array or dflt value if given or undefined

(static) isDST(date) → {boolean}

Description:
  • Returns true if the given date is in DST timezone

Source:
Parameters:
Name Type Description
date Date
Returns:
Type Description
boolean

(static) isDate(val) → {boolean}

Source:
Parameters:
Name Type Description
val any
Returns:
Type Description
boolean

true if the given date is valid

(static) isEmpty(val) → {boolean}

Source:
Parameters:
Name Type Description
val any
Returns:
Type Description
boolean

true of the given value considered empty

(static) isFlag(list, item) → {boolean}

Source:
Parameters:
Name Type Description
list Array.<any>
item any | Array.<any>
Returns:
Type Description
boolean

true if item exists in the array list, search is case sensitive. if item is an array it will return true if any element in the array exists in the list.

(static) isFunc(func) → {function|undefined}

Source:
Parameters:
Name Type Description
func string
Returns:
Type Description
function | undefined

the function itself or undefined if not a function

(static) isMatched(obj, condition, optionsopt)

Description:
  • All properties in the object obj must match all properties in the object condition, for comparison lib.isTrue is used for each property in the condition object.

Source:
Parameters:
Name Type Attributes Description
obj object
condition object
  • if a condition value is null it means an empty or non-existed value,
  • if a condition property is a string/number or regexp then it must match or be equal
  • if a condition property is a list then the object value must be present in the list
  • if an object property is a list and the condition property is a string/number/list then it must be present in the list
  • a condition can be a RegExp to test patterns
options object <optional>

The options can provide specific ops and types per property.

Example
lib.isMatched({ id: 1, name: "test", type: ["user", "admin"] }, { name: /^j/ })
true
lib.isMatched({ id: 1, name: "test", type: ["user", "admin"] }, { type: "admin" }, { ops: { type: "not_in" } })
false
lib.isMatched({ id: 1, name: "test", type: ["user", "admin"] }, { type: [staff"] })
false
lib.isMatched({ id: 1, name: "test", type: ["user", "admin"] }, { id: 1 }, { ops: { id: "ge" } })
true

(static) isNumber(val) → {number|NaN}

Source:
Parameters:
Name Type Description
val any
Returns:
Type Description
number | NaN

itself if the value is a number and not equal 0

(static) isNumeric(val)

Source:
Parameters:
Name Type Description
val any

Return {boolean} true if the value is a number or string representing a number

(static) isObject(val) → {object|undefined}

Source:
Parameters:
Name Type Description
val any
Returns:
Type Description
object | undefined

itself if a regular object and not null

(static) isPositive(val) → {boolean}

Source:
Parameters:
Name Type Description
val any
Returns:
Type Description
boolean

true if a number is positive, i.e. greater than zero

(static) isPrefix(val, prefix) → {boolean}

Source:
Parameters:
Name Type Description
val any
prefix string
Returns:
Type Description
boolean

true if the value is prefixed

(static) isSimilar()

Description:
  • Returns a score between 0 and 1 for two strings, 0 means no similarity, 1 means exactly similar. The default algorithm is JaroWrinkler, options.type can be used to specify a different algorithm:

    • sd - Sorensent Dice
    • cs - Cosine Similarity
Source:

(static) isString(val) → {string}

Source:
Parameters:
Name Type Description
val string
Returns:
Type Description
string

the string value or empty string if not a string

(static) isTimeRange(time1, time2, optionsopt) → {boolean}

Description:
  • Returns 0 if the current time is not within specified valid time range or it is invalid. Only continious time range is supported, it does not handle over the midninght ranges, i.e. time1 is always must be greater than time2.

Source:
Parameters:
Name Type Attributes Description
time1 string
time2 string
options object <optional>
Properties
Name Type Attributes Description
tz int <optional>

to specify timezone, no timezone means current timezone.

date int | Date | string <optional>

if given must be a list of dates in the format: YYY-MM-DD,...

Returns:
Type Description
boolean

(static) isTrue(val, condition, opopt, typeopt) → {boolean}

Description:
  • Evaluate an expr, compare 2 values with optional type and operation, compare a data value val`` against a condtion cond`.

Source:
Parameters:
Name Type Attributes Description
val any
condition object
op string <optional>
type string <optional>
Returns:
Type Description
boolean

true if equal

(static) isUnicode(str) → {string|undefined}

Source:
Parameters:
Name Type Description
str string
Returns:
Type Description
string | undefined

the string iself if contains Unicode characters

(static) isUuid(str) → {string|undefined}

Source:
Parameters:
Name Type Description
str any
Returns:
Type Description
string | undefined

the value represents an UUID

(static) isValidBool(…args) → {boolean}

Source:
Parameters:
Name Type Attributes Description
args any <repeatable>
Returns:
Type Description
boolean

first valid boolean from the list of arguments or false

(static) isValidNum(…args) → {number}

Source:
Parameters:
Name Type Attributes Description
args any <repeatable>
Returns:
Type Description
number

first valid number from the list of arguments or 0

(static) isValidPositive(…args) → {number}

Source:
Parameters:
Name Type Attributes Description
args any <repeatable>
Returns:
Type Description
number

first valid positive number from the list of arguments or 0

(static) isValidVersion(version, conditionopt)

Source:
Parameters:
Name Type Attributes Description
version string
condition string <optional>

can be: >=M.N, >M.N, =M.N, <=M.N, <M.N, M.N-M.N

(static) isWord(text, start, end, delimitersopt) → {boolean}

Source:
Parameters:
Name Type Attributes Description
text string
start int
end int
delimiters string <optional>

define a character set to be used for words boundaries, if not given or empty string the default will be used

Returns:
Type Description
boolean

true if it is a word at the position start and end in the text string,

(static) jsonFormat(obj, optionsopt)

Description:
  • Nicely format an object with indentations, optional indentlevel can be used to control until which level deep to use newlines for objects.

Source:
Parameters:
Name Type Attributes Description
obj object
options object <optional>
Properties
Name Type Attributes Description
preset string <optional>

predefined set of options, compact prints yaml-like text version, if a list all presets are combined

indent string <optional>

initial indent, empty default

ilevel string <optional>

level to start to use spaces for indentation, 0 default

ignore string <optional>

regexp with properties to ingore

skipnull string <optional>

do not print null/undefined/""

skipempty string <optional>

skip all empty object accorsding to lib.isEmpty

map string <optional>

an object to map property names

replace string <optional>

an object for string values replacement: { ORIG: REPL... }

preprocess string <optional>

a function(name, val, options) to run before prints, return undefined to skip

sbracket1, sbracket2 string <optional>

open/close brackets for arrays, [ ]

cbracket1, cbracket2 string <optional>

open close brackets for obejcts, { }

nl1, nl2 string <optional>

newline chars before and after a single property

quote1, quote2 string <optional>

quotes for property names

squote1, squote2 string <optional>

quotes for string values

comma string <optional>

comma separator between items

sep string <optional>

separator between array items, comma by default

space string <optional>

symbol for indentation

nspace string <optional>

how many spaces to use for indentation, 4

prefix string <optional>

prefix for array items, each item on new line, requires nl1

wrap string <optional>

wrap long strings at this length

over string <optional>

number greater than 1 to allow extra characters over wrap length

delim string <optional>

characters that trigger wrapping

(static) jsonFormatPreset(name, options)

Description:
  • Register or update a jsonFormat preset

Source:
Parameters:
Name Type Description
name string
options object

(static) jsonParse(data, optionsopt) → {object|array}

Description:
  • Silent JSON parse, returns null on error, no exceptions raised.

Source:
Parameters:
Name Type Attributes Description
data string

data to be parsed, non string will be returned as is

options object <optional>

additional properties

Properties
Name Type Attributes Description
datatype string <optional>

make sure the result is returned as type: obj, list, str

dflt string <optional>

return this in case of error

empty string <optional>

if true silent about empty input, no logging

logger string <optional>

report in the log with the specified level, log, debug, ...

Returns:
Type Description
object | array

Javascript native object

(static) jsonToBase64(data, secret, optionsopt) → {string}

Description:
  • Stringify JSON into base64 string, if secret is given, sign the data with it

Source:
Parameters:
Name Type Attributes Description
data any
secret string
options object <optional>
Returns:
Type Description
string

(static) killWorkers(filter)

Description:
  • Kill all workers

Source:
Parameters:
Name Type Description
filter string | number | object

see module:lib.getWorkers

(static) loadLocale(file, callbackopt)

Description:
  • Load a file with locale translations into memory

Source:
Parameters:
Name Type Attributes Description
file string
callback function <optional>

(static) localEpoch(typeopt) → {int}

Description:
  • Returns current time in seconds (s), microseconds (m), time struct (tm) or milliseconds since the local lib._epoch (2026-01-01 UTC)

Source:
Parameters:
Name Type Attributes Description
type string <optional>
Returns:
Type Description
int

(static) log(…argsopt)

Description:
  • Print all arguments into the console, for debugging purposes, if the first arg is an error only print the error

Source:
Parameters:
Name Type Attributes Description
args any <optional>
<repeatable>

print all arguments

(static) makePath(dir, callbackopt)

Description:
  • Async version of makePath, stops on first error

Source:
Parameters:
Name Type Attributes Description
dir string
callback function <optional>

(static) makePathSync(dir)

Description:
  • Recursively create all directories, return 1 if created or 0 on error or if exists, no exceptions are raised, error is logged only

Source:
Parameters:
Name Type Description
dir string

(static) matchAllRegexp(str, rx) → {Array.<string>}

Description:
  • Perform match on a regexp and return all matches in an array, if no index is specified returns item 1

Source:
Parameters:
Name Type Description
str string
rx regexp
Returns:
Type Description
Array.<string>

(static) matchRegexp(str, rx, indexopt) → {string}

Description:
  • Perform match on a regexp for a string and returns matched value, if no index is specified returns item 1, using index 0 returns the whole matched string, -1 means to return the whole matched array If the `rx`` object has the 'g' flag the result will be all matches in an array.

Source:
Parameters:
Name Type Attributes Description
str string
rx regexp
index int <optional>
Returns:
Type Description
string

(static) memoryStats() → {object}

Source:
Returns:
Type Description
object

(static) moveFile(src, dst, overwriteopt, callbackopt)

Description:
  • Copy file and then remove the source, do not overwrite existing file

Source:
Parameters:
Name Type Attributes Description
src string
dst string
overwrite boolean <optional>

true to overwrite

callback function <optional>

(static) murmurHash3(key) → {number}

Description:
  • 32-bit MurmurHash3 implemented by bryc (github.com/bryc)

Source:
Parameters:
Name Type Description
key string

input string

Returns:
Type Description
number

hash number

(static) networkInterfaces(optionsopt) → {Array.<object>}

Description:
  • Return a list of local interfaces, default is all active IPv4 unless IPv6`` property is set. Skips 169.254 unless all` is set.

Source:
Parameters:
Name Type Attributes Description
options object <optional>
Returns:
Type Description
Array.<object>

(static) networkStats(netdev, callbackopt) → {object}

Description:
  • Return network stats for the instance, if not netdev is given it uses eth0 (Linux)

Source:
Parameters:
Name Type Attributes Description
netdev string
callback function <optional>

if given pass stats via callback

Returns:
Type Description
object

(static) newError(message, statusopt, codeopt)

Description:
  • Return a new Error object, message can be a string or an object with message, code, status and other properties. The default error status is 400 if not specified.

Source:
Parameters:
Name Type Attributes Description
message string | object
status number | object <optional>

if an object all properties are copied into the error

code string | number <optional>

if provided set as the .code property

Example
lib.newError("not found", 404)
lib.newError("not found", 404, "NOTFOUND")
lib.newError("not found", { status: 404, path: "/..." })
lib.newError({ message: "not found", status: 404, code: 123 })

(static) normalize(…args)

Description:
  • Safe path.normalize, no exceptions

Source:
Parameters:
Name Type Attributes Description
args any <repeatable>

(static) notifyWorkers(filter)

Description:
  • Send a message to all workers

Source:
Parameters:
Name Type Description
filter string | number | object

see module:lib.getWorkers

Example
lib.notifyWorkers("worker:restart", { worker_type: null });

(static) now() → {int}

Description:
  • Return number of seconds for current time

Source:
Returns:
Type Description
int

(static) objClone(obj, …argsopt) → {object}

Description:
  • A shallow copy of an object, it is deeper than Object.assign for arrays, objects, sets and maps, these created new but all other types are just references as in Object.assign

Source:
Parameters:
Name Type Attributes Description
obj object

first argument is the object to clone, can be null

args any <optional>
<repeatable>

additional arguments are treated as object to be merged into the result using Object.assign

Returns:
Type Description
object
Example
const a = { 1: 2, a: [1, 2] }
   const b = lib.objClone(a, { "3": 3, "4": 4 })
   b.a.push(3)
   a.a.length != b.length

(static) objDescr(obj, optionsopt) → {string}

Description:
  • Return an object structure as a string object by showing primitive properties only, for arrays it shows the length and options.count or 25 first items, for objects it will show up to the options.keys or 25 first properties, strings are limited by options.length or 256 bytes, if truncated the full string length is shown. the object depth is limited by options.depth or 5 levels deep, the number of properties are limited by options.count or 15, all properties that match options.ignore will be skipped from the output, if options.allow is a regexp, only properties that match it will be output. Use options.replace for replacing anything in the final string.

Source:
Parameters:
Name Type Attributes Description
obj object
options objects <optional>
Returns:
Type Description
string

(static) objExtend(obj, val, optionsopt) → {object}

Description:
  • Add properties to an existing object where the first arg is an object, the second arg is an object to add properties from, the third argument can be an options object that can control how the properties are merged.

Source:
Parameters:
Name Type Attributes Description
obj object
val object
options object <optional>

Options properties:

  • allow - a regexp which properties are allowed to be merged
  • ignore - a regexp which properties should be ignored
  • del - a regexp which properties should be removed
  • strip - a regexp to apply to each property name before merging, the matching parts will be removed from the name
  • deep - extend all objects not just the top level
  • noempty - skip undefined, default is to keep
Returns:
Type Description
object
Example
lib.objExtend({ a:1, c:5 }, { c: { b: 2 }, d: [{ d: 3 }], _e: 4, f: 5, x: 2 }, { allow: /^(c|d|_e)/, strip: /^_/, del: /^f/ })
{ a: 1, c: { b: 2 }, d: [ { d: 3 } ], e: 4 }

lib.objExtend({ a:1, c:5 }, { c: { b: 2 }, d: [{ d: 3 }], _e: 4, f: 5, x: 2 }, { allow: /^(c|d|_e)/, strip: /^_/, del: /^f/, deep: 1 })
{ a: 1, c: {}, d: [ { d: 3 } ], e: 4 }

(static) objFlatten(obj, optionsopt) → {object}

Description:
  • Flatten a javascript object into a single-depth object, all nested values will have property names appended separated by comma

Source:
Parameters:
Name Type Attributes Description
obj object
options object <optional>
  • separator - use something else instead of .
  • index - initial index for arrays, 0 is default
  • ignore - regexp with properties to ignore
Returns:
Type Description
object
Example
> lib.objFlatten({ a: { c: 1 }, b: { d: 1 } } )
{ 'a.c': 1, 'b.d': 1 }
> lib.objFlatten({ a: { c: 1 }, b: { d: [1,2,3] } }, { index: 1 })
{ 'a.c': 1, 'b.d.1': 1, 'b.d.2': 2, 'b.d.3': 3 }

(static) objGet(obj, name, optionsopt) → {any}

Description:
  • Return a property from the object, name specifies the path to the property, if the required property belong to another object inside the top one the name uses . to separate objects. This is a convenient method to extract properties from nested objects easily.

Source:
Parameters:
Name Type Attributes Description
obj object
name string
options object <optional>

Options may contains the following properties:

  • list - return the value as a list even if there is only one value found
  • obj - return the value as an object, if the result is a simple type, wrap into an object like { name: name, value: result }
  • str - return the value as a string, convert any other type into string
  • num - return the value as a number, convert any other type by using toNumber
  • func - return the value as a function, if the object is not a function returns null
  • owner - return the owner object, not the value, i.e. return the object who owns the value specified in the name
Returns:
Type Description
any
Example
> lib.objGet({ response: { item : { id: 123, name: "Test" } } }, "response.item.name")
"Test"
> lib.objGet({ response: { item : { id: 123, name: "Test" } } }, "response.item.name", { list: 1 })
[ "Test" ]
> lib.objGet({ response: { item : { id: 123, name: "Test" } } }, "response.item.name", { owner: 1 })
{ item : { id: 123, name: "Test" } }

(static) objIncr(obj, name, count, resultopt)

Description:
  • Increment a property by the specified number, if the property does not exist it will be created, returns new incremented value or the value specified by the result argument. It uses lib.objSet so the property name can be a nested path.

Source:
Parameters:
Name Type Attributes Default Description
obj object
name string
count number
result string <optional>
new

(static) objKeys(obj) → {Array.<string>}

Description:
  • Return all property names for an object

Source:
Parameters:
Name Type Description
obj object
Returns:
Type Description
Array.<string>

(static) objMerge(obj, options) → {object}

Description:
  • Merge two objects, all properties from the val override existing properties in the obj, returns a new object

Source:
Parameters:
Name Type Description
obj object
options object
  • allow - a regexp which properties are allowed to be merged
  • ignore - a regexp which properties should be ignored
  • del - a regexp which properties should be removed
  • remove - a regexp to apply to each property name before merging, the matching parts will be removed from the name
  • deep - make a deep copy using objExtend
Returns:
Type Description
object
Example
var o = lib.objMerge({ a:1, b:2, c:3 }, { c:5, d:1, _e: 4, f: 5, x: 2 }, { allow: /^(c|d)/, remove: /^_/, del: /^f/ })
o = { a:1, b:2, c:5, d:1 }

(static) objMult(obj, name, count, resultopt)

Description:
  • Similar to objIncr but does multiplication

Source:
Parameters:
Name Type Attributes Default Description
obj object
name string
count number
result strings <optional>
new

(static) objSearch(obj, optionsopt)

Description:
  • Return list of objects that matched the given criteria in the given object. Performs the deep search.

Source:
Parameters:
Name Type Attributes Description
obj object
options object <optional>
  • exists - search by property name, return all objects that contain given property
  • hasValue - return only objects that have a property with given value
  • matchValue - return only objects that match the given RegExp by property value
  • matchName - return only objects that match the given RegExp by property name
  • sort - sort the result by the given property
  • value - return an object with this property only, not the whole matched object
  • count - return just number of found properties
Example
var obj = { id: { index: 1 }, name: { index: 3 }, descr: { type: "string", pub: 1 }, items: [ { name: "test" } ] };

lib.objSearch(obj, { matchValue: /string/ });
[ { name: 'descr', value: { type: "string", pub: 1 } } ]

lib.objSearch(obj, { matchName: /name/, matchValue: /^t/ });
[{ name: '0': value: { name: "test" }]

lib.objSearch(obj, { exists: 'index', sort: 1, value: "index" });
{ id: 1, name: 3 }

lib.objSearch(obj, { hasValue: 'test', count: 1 });
1

(static) objSet(obj, name, value, optionsopt) → {any}

Description:
  • Set a property of the object, name can be an array or a string with property path inside the object, all non existent intermediate objects will be create automatically. The options can have the folowing properties:

Source:
Parameters:
Name Type Attributes Description
obj object
name string
value any
options object <optional>
  • incr - increment a numeric property with the given number or 1, 0 is noop, non-existing propertties will be initilaized with 0
  • mult - multiply a numeric property with the given number, non-existing properties will be initialized with 0
  • push - add to the array, if it is not an array a new empty aray is created
  • append - append to a string
  • unique - only push if not in the list
  • separator - separator for object names, default is .
  • result - "new" - new value, "old" - old value, "obj" - final object, otherwise the original object itself
Returns:
Type Description
any
Example
var a = lib.objSet({}, "response.item.count", 1)
lib.objSet(a, "response.item.count", 1, { incr: 1 })

(static) objSize(optionsopt) → {int}

Description:
  • Calculate the size of the whole object, this is not exact JSON size, for speed it summarizes approximate size of each property recursively

Source:
Parameters:
Name Type Attributes Description
options object <optional>
Properties
Name Type Attributes Description
depth int <optional>

limits how deep it goes, on limit returns MAX_SAFE_INTEGER+ number

nan boolean <optional>

if true return NaN on reaching the limits

pad int <optional>

extra padding added for each property, default is 5 to simulate JSON encoding, "..": ".."

Returns:
Type Description
int

the size of the whole object

(static) parallel(tasks, callbackopt, directopt)

Description:
  • Execute a list of functions in parallel and execute a callback upon completion or occurance of an error. Each function will be passed a callback to signal completion. The callback accepts an error for the first argument. The iterator and callback will be called via setImmediate function to allow the main loop to process I/O unless the direct argument is true

Source:
Parameters:
Name Type Attributes Description
tasks Array.<function()>
callback function <optional>
direct boolean <optional>

(static) parseCookies(header) → {object}

Description:
  • Parse a cookie header.

    Parse the given cookie header string into an object The object has the various cookies as keys(names) => values Borrowed from https://github.com/jshttp/cookie

Source:
Parameters:
Name Type Description
header string

Cookie header

Returns:
Type Description
object

(static) parseTime(time) → {Array.<int>}

Description:
  • Parses a string with time and return an array [hour, min], accepts 12 and 24hrs formats, a single hour is accepted as well, returns undefined if cannot parse

Source:
Parameters:
Name Type Description
time string
Returns:
Type Description
Array.<int>

(static) phraseSplit(str, optionsopt) → {Array.<string>}

Description:
  • Split a string into phrases separated by options.separator character(s) and surrounded by characters in options.quotes. The default separator is space and default quotes are both double and single quote.

Source:
Parameters:
Name Type Attributes Description
str string
options object <optional>
Properties
Name Type Attributes Description
keepempty boolean <optional>

is given all empty parts will be kept in the list.

Returns:
Type Description
Array.<string>

(static) random(sizeopt) → {string}

Description:
  • Generate random key, size if specified defines how many random bits to generate

Source:
Parameters:
Name Type Attributes Default Description
size int <optional>
256
Returns:
Type Description
string

(static) randomBytes(sizeopt, encodeopt) → {string|Buffer}

Description:
  • Generates cryptographically strong pseudorandom data. The size argument is a number indicating the number of bytes to generate. By default encode is "hex", can be any encoding supported by Buffer, "binary" returns Buffer itself.

Source:
Parameters:
Name Type Attributes Default Description
size int <optional>
8
encode string <optional>
hex
Returns:
Type Description
string | Buffer

(static) randomFloat() → {number}

Description:
  • Returns random number between 0 and 1, 32 bits

Source:
Returns:
Type Description
number

(static) randomInt(min, max) → {number}

Description:
  • Return random integer between min and max inclusive using crypto generator, based on https://github.com/joepie91/node-random-number-csprng

Source:
Parameters:
Name Type Description
min int
max int
Returns:
Type Description
number

(static) randomNum(min, max, decsopt) → {number}

Description:
  • Generates a random number between given min and max (required) Optional third parameter indicates the number of decimal points to return:

    • If it is not given or is NaN, random number is unmodified
    • If >0, then that many decimal points are returned (e.g., "2" -> 12.52
Source:
Parameters:
Name Type Attributes Description
min int
max int
decs int <optional>
Returns:
Type Description
number

(static) randomShort() → {number}

Description:
  • Return random number between 0 and SHORT_MAX

Source:
Returns:
Type Description
number

(static) randomUInt() → {number}

Description:
  • Return random number between 0 and ULONG_MAX

Source:
Returns:
Type Description
number

(static) randomUShort() → {number}

Description:
  • Return random number between 0 and USHORT_MAX

Source:
Returns:
Type Description
number

(static) readFile(file, optionsopt, callbackopt)

Description:
Source:
Parameters:
Name Type Attributes Description
file string
options object <optional>
callback function <optional>

(static) readFileSync(file, optionsopt) → {string|Buffer}

Description:
  • Return contents of a file, empty if not exist or on error.

Source:
Parameters:
Name Type Attributes Description
file string
options object <optional>
  • cfg - parse file in config format, name=value per line, return a list of args
  • json - parse file as JSON, return an object, in case of error an empty object
  • xml - parse the file as XML, return an object
  • list - split contents with the given separator
  • encoding - file encoding when converting to string, "binary" to return Buffer
  • logger - log level for error messages
  • missingok - if set ENOENT will not be logged
  • offset - read from the position in the file, if negative the offset is from the end of file
  • length - read only this much of the data, otherwise read till the end of file
Returns:
Type Description
string | Buffer

(static) replaceRegexp(str, rx, val) → {string}

Description:
  • Safe version of replace for strings, always returns a string, if val is not provided performs removal of the matched patterns

Source:
Parameters:
Name Type Description
str string
rx regexp
val string
Returns:
Type Description
string

(static) runCallback()

Description:
  • Run delayed callback for the message previously registered with the deferCallback method. The message must have __deferId property which is used to find the corresponding callback, if the msg is a JSON string it will be converted into the object.

    Same parent object must be used for deferCallback and this method.

Source:

(static) series(tasks, callbackopt, directopt)

Description:
  • Execute a list of functions serially and execute a callback upon completion or occurance of an error. Each function will be passed a callback to signal completion. The callback accepts either an error for the first argument in which case the flow will be aborted and the final callback will be called immediately or some optional data to be passed to thr next iterator function as a second argument.

    The iterator and callback will be called via setImmediate function to allow the main loop to process I/O unless the direct argument is true

Source:
Parameters:
Name Type Attributes Description
tasks Array.<function()>
callback function <optional>
direct boolean <optional>
Example
lib.series([
   function(next) {
       next(null, "data");
   },
   function(next, data) {
      setTimeout(function () { next(null, data); }, 100);
   },
], (err, data) => {
   console.log(err, data);
});

(static) sfuuid(optionsopt)

Description:
  • Generate a SnowFlake unique id as 64-bit number Format: time - 41 bit, node - 10 bit, counter - 12 bit

Source:
Parameters:
Name Type Attributes Description
options object <optional>
Properties
Name Type Attributes Description
now int <optional>

time, if not given local epoch clock is used in microseconds

epoch int <optional>

local epoch type via module:lib.localEpoch, default is milliseconds, m for microseconds, s for seconds

node int <optional>

node id, limited to max 1024

radix int <optional>

default is 10, use any value between 2 - 36 for other numeric encoding

(static) shuffle(list) → {Array.<any>}

Description:
  • Randomize a list items in place

Source:
Parameters:
Name Type Description
list Array.<any>
Returns:
Type Description
Array.<any>

(static) sign(key, data, algorithmopt, encodeopt) → {string}

Description:
  • HMAC signing and base64 encoded, default algorithm is sha1

Source:
Parameters:
Name Type Attributes Default Description
key string
data string | Buffer
algorithm toString <optional>
sha1
encode string <optional>
base64
Returns:
Type Description
string

(static) sleep(delay) → {Promise}

Description:
  • Async sleep version

Source:
Parameters:
Name Type Description
delay int

number of milliseconds to wait

Returns:
Type Description
Promise

(static) slug(optionsopt) → {string}

Description:
  • Generate a 22 chars slug from an UUID

Source:
Parameters:
Name Type Attributes Description
options object <optional>
Properties
Name Type Attributes Description
alphabet string <optional>

chars allowed in hashids, default is lib.uriSafe

prefix string <optional>

repend with prefix

Returns:
Type Description
string

(static) sortByVersion()

Description:
  • Sort a list be version in descending order, an item can be a string or an object with a property to sort by, in such case name must be specified which property to use for sorting. The name format is assumed to be: XXXXX-N.N.N

Source:

(static) spawnProcess(cmd, args, optionsopt, callbackopt) → {ChildProcess}

Description:
  • Run specified command with the optional arguments, this is similar to child_process.spawn with callback being called after the process exited

Source:
Parameters:
Name Type Attributes Description
cmd string
args string | Array.<string>
options object <optional>

options for the child_processes.spawn

Properties
Name Type Attributes Description
stdio boolean <optional>

if pipe then capture and return stdout/stderr in callback

callback function <optional>

(err, stdout, stderr)

Returns:
Type Description
ChildProcess
Example
lib.spawProcess("ls", "-ls", { cwd: "/tmp" }, lib.log)

(static) spawnSeries(cmds, optionsopt, callbackopt)

Description:
  • Run a series of commands, if stdio is a pipe then output from all commands is concatenated.

Source:
Parameters:
Name Type Attributes Description
cmds object

is an object where a property name is a command to execute and the value is an array of arguments or null.

options object <optional>

if options.error is 1, then stop on first error or if non-zero status on a process exit.

callback function <optional>

(err, stdout, stderr)

Example
lib.spawnSeries({"ls": "-la",
                 "ps": "augx",
                 "du": { argv: "-sh", stdio: "inherit", cwd: "/tmp" },
                 "uname": ["-a"] },
lib.log)

(static) split(str, sepopt, optionsopt) → {Array.<string>}

Description:
  • Split string into array, ignore empty items by default

Source:
Parameters:
Name Type Attributes Default Description
str string

If str is an array and type is not specified then all non-string items will be returned as is.

sep RegExp | string <optional>
,|

separator

options object <optional>
Properties
Name Type Attributes Description
datatype string <optional>

will be used with lib.toValue to convert the value for each item

keepempty boolean <optional>

will preserve empty items, by default empty strings are ignored

notrim boolean <optional>

will skip trimming strings, trim is the default

max int <optional>

will skip strings over the specificed size if no trunc

trunc boolean <optional>

will truncate strings longer than max

regexp regexp <optional>

will skip string if not matching

noregexp regexp <optional>

will skip string if matching

number boolean <optional>

convert into a number

cap boolean <optional>

capitalize

camel boolean <optional>

camelize

lower boolean <optional>

lowercase

upper boolean <optional>

uppercase

strip string | regexp <optional>

remove occurences

replace object <optional>

an object map which characters to replace with new values

range boolean <optional>

will parse numeric ranges in the format NUM-NUM and add all numbers in between, invalid ranges are skipped

unique boolean <optional>

remove duplicate entries

Returns:
Type Description
Array.<string>

(static) sprintf(fmt, …args)

Description:
  • C-sprintf alike, based on http://stackoverflow.com/a/13439711

Source:
Parameters:
Name Type Attributes Description
fmt string
args any <repeatable>
Example
sprintf(fmt, arg, ...)

(static) statSync(file) → {object}

Description:
  • Non-exception version, returns empty object, mtime is 0 in case file does not exist or number of seconds of last modified time mdate is a Date object with last modified time

Source:
Parameters:
Name Type Description
file string
Returns:
Type Description
object

(static) strCompress()

Description:
  • From https://github.com/pieroxy/lz-string/

Source:

(static) strDecompress()

Source:

(static) strTrim(str, charsopt) → {string}

Description:
  • Remove all whitespace from the begining and end of the given string, if an array with characters is not given then it trims all whitespace

Source:
Parameters:
Name Type Attributes Description
str string
chars string <optional>
Returns:
Type Description
string

(static) strWrap(str, optionsopt) → {string}

Description:
  • Wrap a long string

Source:
Parameters:
Name Type Attributes Description
str string
options object <optional>
  • wrap - max length, 80 default
  • nl - newline character, \n default
  • delim - delimiters for breaking the line, space is default
  • over - percentage over 1 how long to go for delimiter
  • indent - prefix for every line wrapped
  • quotes - a single quote symbol or list with opening and closing quotes
Returns:
Type Description
string

(static) strftimeMap(date, fmt, optionsopt) → {toString}

Description:
  • Format date object according to Unix stftime function

Source:
Parameters:
Name Type Attributes Description
date string | number | Date
fmt string
options object <optional>
Returns:
Type Description
toString

(static) stringify(obj, replaceropt, spaceopt)

Description:
  • JSON stringify without exceptions, on error just returns an empty string and logs the error

Source:
Parameters:
Name Type Attributes Description
obj any
replacer function <optional>
space string | number <optional>

(static) suuid(prefixopt, optionsopt) → {string}

Description:
  • Short unique id within a microsecond or local epoch

Source:
Parameters:
Name Type Attributes Description
prefix string <optional>

prepend with prefix

options object <optional>

same options as for module:lib.getHashid

Properties
Name Type Attributes Description
epoch int <optional>

local epoch type via module:lib.localEpoch, default is milliseconds, m for microseconds, s for seconds

Returns:
Type Description
string

generated hash

(static) testRegexp(str, rx) → {string}

Description:
  • Perform test on a regexp for a string and returns true only if matched.

Source:
Parameters:
Name Type Description
str string
rx regexp
Returns:
Type Description
string

(static) testRegexpObj()

Description:
  • Run test on a regexpObj

Source:

(static) textToEntity(str) → {string}

Description:
  • Convert all special symbols into html entities

Source:
Parameters:
Name Type Description
str string
Returns:
Type Description
string

(static) textToXml(str) → {string}

Description:
  • Convert all special symbols into xml entities

Source:
Parameters:
Name Type Description
str string
Returns:
Type Description
string

(static) timingSafeEqual(a, b) → {boolean}

Description:
  • Timing safe string compare using double HMAC, from suryagh/tsscmp

Source:
Parameters:
Name Type Description
a string | Buffer
b string | Buffer
Returns:
Type Description
boolean

(static) toBase32(bug, optionsopt) → {string}

Description:
  • Convert a Buffer into base32 string

Source:
Parameters:
Name Type Attributes Description
bug Buffer

inout buffer

options object <optional>
Properties
Name Type Attributes Description
alphabet string <optional>

alphabet to use for encoding, default is base32

padding boolean <optional>

if true add padding using =

Returns:
Type Description
string

encoded value

(static) toBase62(num, alphabet) → {string}

Description:
  • Return base62 representation for a number

Source:
Parameters:
Name Type Description
num number
alphabet string
Returns:
Type Description
string

(static) toBase64url(str) → {string}

Description:
  • Encode a string into Base64 url safe version

Source:
Parameters:
Name Type Description
str string | Buffer | ArrayBuffer
Returns:
Type Description
string

(static) toBool(val, dfltopt) → {boolean}

Description:
  • Return true if value represents true condition, i.e. non empty value including yes, ok , t

Source:
Parameters:
Name Type Attributes Description
val string | number | boolean
dflt any <optional>
Returns:
Type Description
boolean

(static) toCamel(name, charsopt) → {string}

Description:
  • Convert into camelized form

Source:
Parameters:
Name Type Attributes Description
name string
chars string <optional>

can define the separators, default is [ _.:-]

Returns:
Type Description
string

(static) toDate(val, dfltopt, invalidopt) → {Date}

Description:
  • Return Date object for given text or numeric date representation, for invalid date returns 1969 unless invalid parameter is given, in this case invalid date returned as null. If dflt is NaN, null or 0 returns null as well.

Source:
Parameters:
Name Type Attributes Description
val string | Date | number
dflt any <optional>
invalid boolean <optional>
Returns:
Type Description
Date

(static) toDigits(str) → {string}

Description:
  • Strip all non-digit characters from a string

Source:
Parameters:
Name Type Description
str string

input string

Returns:
Type Description
string

only digit in the result

(static) toDuration(mtime, optionsopt) → {string}

Description:
  • Given time in milliseconds, return how long ago it happened

Source:
Parameters:
Name Type Attributes Description
mtime number
options object <optional>
Properties
Name Type Attributes Description
age boolean | int <optional>

if true make it duration from now or if age > 1 then since that date in milliseconds

short boolean <optional>

if true use first letters only

round boolean <optional>

a number, 1 return only 1st part, 2 - 1st and 2nd parts

Returns:
Type Description
string

(static) toEmail(val, optionsopt) → {string}

Description:
  • Return an email address if valid

Source:
Parameters:
Name Type Attributes Description
val string
options object <optional>
Properties
Name Type Attributes Description
parse boolean <optional>

extract the email from name <email> format]

max int <optional>

return "" if length greater than this

Returns:
Type Description
string

(static) toFlags(cmd, list, name) → {Array.<string>}

Description:
  • Flags command utility, the commands are:

Source:
Parameters:
Name Type Description
cmd string
  • add - adds the name flags to the list if does not exists, returns the same array
  • update - adds new flags and removes flags that starts with - , returns the same array
  • concat - same as add but always returns a new list
  • del - removes the flags name, returns the same array
  • present - returns only flags that present in the list name
  • absent - returns only flags that are not present in the list name
list Array.<string>
name string | Array.<string>
Returns:
Type Description
Array.<string>

(static) toFormat(format, data, optionsopt)

Description:
  • Convert a list of records into the specified format, supported formats are: xml, csv, json, jsontext.

Source:
Parameters:
Name Type Attributes Description
format string
  • For csv the default separator is comma but can be specified with options.separator. To produce columns header specify options.header.
  • For json format puts each record as a separate JSON object on each line, so to read it back it will require to read every line and parse it and add to the list.
  • For xml format the name of the row tag is <row> but can be specified with options.tag.
data object | Array.<object>
options object <optional>
Properties
Name Type Attributes Default Description
allow Array.<string> <optional>

which is a list of property names that are allowed only in the output for each record, non-existent properties will be replaced by empty strings.

mapping object <optional>

object property can redefine different tag/header names to be put into the file instead of the exact column names from the records.

quotes string <optional>
"

quotes for CSV

separator string <optional>
,

CSV field separator

(static) toMap(val, optionsopt) → {object}

Description:
  • Convert to an object from as string of key:val,... pairs

Source:
Parameters:
Name Type Attributes Description
val string
options object <optional>
Properties
Name Type Attributes Description
delimiter boolean <optional>

pairs separator

separator boolean <optional>

key and value separator

empty boolean <optional>

keep empty keys

noempty boolean <optional>

ignore empty values

mapcamel boolean <optional>

camelize keys

maptype string <optional>

convert values to this type

Returns:
Type Description
object
Example
lib.toMap("a:1,b:2,c:4:5")
{ a: '1', b: '2', c: [ '4', '5' ] }

(static) toMilliseconds(duration) → {number|undefined}

Description:
  • Parse the given duration and return milliseconds.

Source:
Parameters:
Name Type Description
duration string
Returns:
Type Description
number | undefined
Example
lib.toMilliseconds('-3 day')
-259200000
lib.toMilliseconds('2.5 hrs')
9000000
lib.toMilliseconds('1m')
60000
lib.toMilliseconds('2.5 hr')
9000000
lib.toMilliseconds('2.5 mon')
6480000000

(static) toMtime(val, dfltopt) → {number}

Description:
  • Return milliseconds from the date or date string, only number as dflt is supported, for invalid dates returns 0

Source:
Parameters:
Name Type Attributes Description
val string | number | Date
dflt any <optional>
Returns:
Type Description
number

(static) toNumber(val, optionsopt) → {number}

Description:
  • Safe convertion to a number, no expections, uses 0 instead of NaN, handle booleans, if float specified, returns as float.

Source:
Parameters:
Name Type Attributes Description
val any

to be converted to a number

options object <optional>
Properties
Name Type Attributes Description
dflt int <optional>

default value

float int <optional>

treat as floating number

min int <optional>

minimal value, clip

max int <optional>

maximum value, clip

incr int <optional>

a number to add before checking for other conditions

mult int <optional>

a number to multiply before checking for other conditions

novalue int <optional>

replace this number with default

zero int <optional>

replace with this number if result is 0

digits int <optional>

how many digits to keep after the floating point

bigint int <optional>

return BigInt if not a safe integer

Returns:
Type Description
number
Example
lib.toNumber("123")
lib.toNumber("1.23", { float: 1, dflt: 0, min: 0, max: 2 })

(static) toParams(query, schema, optionsopt) → {string|object}

Description:
  • Process incoming query and convert parameters according to the type definition, the schema contains the definition of the paramaters against which to validate incoming data. It is an object with property names and definitoons that at least must specify the type, all other options are type specific.

    Returns a string message on error or an object

Source:
Parameters:
Name Type Attributes Description
query object

request query object, usually req.query or req.body

schema object

an object in format: { name: module:lib.ParamsOptions, ...}

options object <optional>

options can define the following properties to customize convertion:

Properties
Name Type Attributes Description
null boolean <optional>

always return null on any error

setnull boolean <optional>

if the value is equal this or any value if an array then set property to null, useful to reset lists, maps...

existing boolean <optional>

skip properties if not present in the query

prefix string <optional>

prefix to be used when searching for the parameters in the query, only properties with this prefix will be processed. The resulting object will not have this prefix in the properties.

dprefix string <optional>

prefix to use when checking for defaults, defaults are checks in this order: dprefix+name, name, *.type, *

defaults object <optional>

to pass realtime or other custom options for the validation or convertion utilities as the first argument if not defined in the definition, this is the place to customize/add/override global parameter conditions without changing it. Exact parameter name is used or a wildcard in the format *.type where type id any valid type supported or just * for all parameters. Special default '**' is always applied to all parameters.

Returns:
Type Description
string | object

string in case of an error or an object

Example
var query = lib.toParams(req.query, {
       id: { type: "int" },
       count: { type: "int", min: 1, max: 10, dflt: 5 },
       age: { type: "int", minnum: 10, maxnum: 99 },
       name: { type: "string", max: 32, trunc: 1 },
       pair: { type: "map", maptype: "int" },
       code: { type: "string", regexp: /^[a-z]-[0-9]+$/, errmsg: "Valid code is required" },
       start: { type: "token", required: 1 },
       email: { type: "list", datatype: "email", novalue: ["a@a"] },
       email1: { type: "email", required: { email: null } },
       data: { type: "json", datatype: "obj" },
       mtime: { type: "mtime", name: "timestamp" },
       date: { type: "date", mindate: new Date(2000,1,1) },
       flag: { type: "bool", novalue: false },
       descr: { novalue: { name: "name", value: "test" }, replace: { "<": "!" } },
       internal: { ignore: 1 },
       tm: { type: "timestamp", optional: 1 },
       ready: { value: "ready" },
       state: { values: [ "ok","bad","good" ] },
       status: { value: [ "ok","done" ] },
       obj: { type: "obj", params: { id: { type: "int" }, name: {} } },
       arr: { type: "array", params: { id: { type: "int" }, name: {} } },
       ssn: { type: "string", regexp: /^[0-9]{3}-[0-9]{3}-[0-9]{4}$/, errmsg: "Valid SSN is required" },
       phone: { type: "list", datatype: "number" },
       }, {
       defaults: {
           start: { secret: req.user.secret },
           name: { dflt: "test" },
           count: { max: 100 },
           email: { ignore: req.user.roles != "admin" },
           "*.string": { max: 255 },
           '*': { maxlist: 255 },
       });

if (typeof query == "string) return api.sendReply(res, 400, query);

(static) toPrice(num, optionsopt)

Description:
  • Return a test representation of a number according to the money formatting rules,

Source:
Parameters:
Name Type Attributes Description
num number
options object <optional>
Properties
Name Type Attributes Default Description
locale string <optional>
en-US
currency string <optional>
USD
display string <optional>
symbol
sign string <optional>
standard
min int <optional>
2
max int <optional>
3

(static) toRFC3339(dateopt) → {string}

Description:
  • Return RFC3339 formatted timestamp for a date or current time

Source:
Parameters:
Name Type Attributes Description
date string <optional>
Returns:
Type Description
string

(static) toRegexp(str, optionsopt)

Description:
  • Safely create a regexp object, if invalid returns undefined, the options can be a string with srandard RegExp flags or an object with the following properties:

Source:
Parameters:
Name Type Attributes Description
str string
options object <optional>
Properties
Name Type Attributes Description
ingoreCase boolean <optional>

similar to i

globalMatch boolean <optional>

similar to m

multiLine boolean <optional>

similar to m

unicode boolean <optional>

similar to u

sticky boolean <optional>

similar to y

escape boolean <optional>

escape all special symbols or symbol e

RegExp

(static) toRegexpMap(obj, val, optionsopt) → {Array.<object>}

Description:
  • Add a regexp to the list of regexp objects, this is used in the config type regexpmap.

Source:
Parameters:
Name Type Attributes Description
obj Array.<object>
val string
options object <optional>
Returns:
Type Description
Array.<object>

in format [ { rx, list }, { rx, list }]

(static) toRegexpObj(obj, val, optionsopt) → {object}

Description:
  • Add a regexp to the object that consist of list of patterns and compiled regexp, this is used in the config type regexpobj

Source:
Parameters:
Name Type Attributes Description
obj object
val string
options object <optional>
Returns:
Type Description
object

in format { list, rx }

(static) toSize(size, decimalsopt)

Description:
  • Return size human readable format

Source:
Parameters:
Name Type Attributes Default Description
size number
decimals boolean <optional>
2

(static) toSkip32(op, key, num) → {number}

Description:
  • Encrypt/decrypt a number using a 10 byte key array, op == d for decrypt, other is encrypt

    based on public domain javascript implementation of:

    SKIP32 -- 32 bit block cipher based on SKIPJACK. Written by Greg Rose, QUALCOMM Australia, 1999/04/27. In common: F-table, G-permutation, key schedule. Different: 24 round feistel structure. Based on: Unoptimized test implementation of SKIPJACK algorithm Panu Rissanen bande@lut.fi SKIPJACK and KEA Algorithm Specifications Version 2.0 29 May 1998

Source:
Parameters:
Name Type Description
op string
key string
num number
Returns:
Type Description
number

(static) toString(val) → {string}

Description:
  • Convert a value to a string, use default Javascript toString convertion of any object, null|undefined will return ""

Source:
Parameters:
Name Type Description
val any
Returns:
Type Description
string

(static) toTemplate(text, obj, optionsopt)

Description:
  • Given a template with @..@ placeholders, replace each placeholder with the value from the obj.

    To use @ in the template specify it as @@

    Placeholders can have default or/and encoding

    • default only: @name|dflt@
    • encoding with default: @name|dflt|encoding@
    • encoding no default: @name||encoding@

    Default placeholders:

    • @exit@ - stop processing and return the template ignoring the rest
    • @RAND@ - produce a random number using Math.random
    • @n@ - produce a line break, newline
    • @p@ - produce 2 newlines
Source:
Parameters:
Name Type Attributes Description
text string
obj object | Array.<object>

can be an object or an array of objects in which case all objects will be checked for the value until non empty.

options object <optional>
Properties
Name Type Attributes Description
allow Array.<string> <optional>

placeholders with a name present in this list will be replaced, all other will be replaced with empty string

skip Array.<string> <optional>

placeholders with a name present in this list will be ignored, the placeholer will be kept

only Array.<string> <optional>

placeholders with a name present in this list will be replaced only, all other will be ignored and kept as placeholders

encoding string <optional>

can be url or base64, the replaced values will be encoded accordingly Encoding options:

  • url, base64, entity, strftime, mtime
  • d-url, d-base64, d-entity - decode value instead of encode it
separator1 string <optional>

left side of the placehoder, default is @

separator2 string <optional>

right side of the placeholder, default is @

Example
lib.toTemplate("http://www.site.com/@code@/@id@", { id: 123, code: "YYY" }, { encoding: "url" })
lib.toTemplate("Hello @name|friend@!", {})

(static) toTitle(name, minlenopt) → {string}

Description:
  • Convert text into capitalized words, if it is less or equal than minlen leave it as is

Source:
Parameters:
Name Type Attributes Description
name string
minlen int <optional>
Returns:
Type Description
string

(static) toUncamel(str, sepopt) → {string}

Description:
  • Convert Camel names into names separated by the given separator or dash(-) if not.

Source:
Parameters:
Name Type Attributes Description
str string
sep string <optional>
Returns:
Type Description
string

(static) toUrl(str, optionsopt) → {string|URL}

Description:
  • Return a well formatted and validated url or parsed URL object

Source:
Parameters:
Name Type Attributes Description
str string
options object <optional>
Properties
Name Type Attributes Description
url boolean <optional>

if true return the URL object not string

Returns:
Type Description
string | URL

(static) toValue(val, typeopt, optionsopt) → {string|number|object|any}

Description:
  • Convert a value to the proper type, default is to return a string or convert the value to a string if no type is specified, options is passed to all lib.toXXX functions as is, so type specific properties can be used.

Source:
Parameters:
Name Type Attributes Description
val any
type string <optional>
  • null|"" - return the value as is without any conversion
  • auto - detect type with module:lib.autoType
  • js - parse JSON into object or array
  • set|list|array - use module.lib.split to convert into a list
  • map - use module.lib.toMap to convert into an object
  • real|float|double|decimal - to floating number
  • int|long|number|now|counter|bigint - a number
  • bool|boolean - boolean value
  • date|time|datetime|timestamp - a Date object
  • mtime - convert date into milliseconds
  • url - use module.lib.toUrl
  • email - use module.lib.toEmail
  • phone|e164 - validate and convert into a valid phone number with only digits
  • json - stringify a value
options object <optional>
Returns:
Type Description
string | number | object | any

(static) toVersion(str) → {number}

Description:
  • Returns a floating number from the version string, it assumes common semver format as major.minor.patch, all non-digits will be removed, underscores will be treated as dots. Returns a floating number which can be used in comparing versions.

Source:
Parameters:
Name Type Description
str string

version like string

Returns:
Type Description
number
Example
> lib.toVersion("1.0.3")
     1.000003
     > lib.toVersion("1.0.3.4")
     1.000003004
     > lib.toVersion("1.0.3.4") > lib.toVersion("1.0.3")
     true
     > lib.toVersion("1.0.3.4") > lib.toVersion("1.0.0")
     true
     > lib.toVersion("1.0.3.4") > lib.toVersion("1.1.0")
     false

(static) totp(key, optionsopt) → {number}

Description:
  • Create a Timed One-Time Password, RFC6328

Source:
Parameters:
Name Type Attributes Description
key string
options object <optional>
Returns:
Type Description
number

(static) traceError(err)

Description:
  • Returns the error stack or the error itself, to be used in error messages

Source:
Parameters:
Name Type Description
err Error

(static) tryCall(callback, …argsopt) → {any}

Description:
  • Run a callback if a valid function, all arguments after the callback will be passed as is, report a warning if callback is not a function but not empty

Source:
Parameters:
Name Type Attributes Description
callback function

try to call this function

args any <optional>
<repeatable>

pass the rest arguments to the function

Returns:
Type Description
any

the function result

(static) tryCatch(callback, …argsopt)

Description:
  • Run a callback inside try..catch block, all arguments after the callback will be passed as is, in case of error all arguments will be printed in the log. If no callback passed do nothing.

Source:
Parameters:
Name Type Attributes Description
callback function

try to call this function

args any <optional>
<repeatable>

pass the rest arguments to the function

(static) tryLater(callback, timeout, …argsopt)

Description:
  • Run a callback after timeout, returns a function so it can be used instead of actual callback, report a warning if callback is not a function but not empty

Source:
Parameters:
Name Type Attributes Description
callback function

try to call this function

timeout int

timeout in milliseconds

args any <optional>
<repeatable>

pass the rest arguments to the function

(static) tryRequire(path, optionsopt) → {object|undefined}

Description:
  • Try loading a module, log if failed, no expection is raised

Source:
Parameters:
Name Type Attributes Description
path string

module path

options object <optional>
Properties
Name Type Attributes Description
logger string <optional>

use logger level

message string <optional>

additional error message

Returns:
Type Description
object | undefined

(static) typeName(value) → {string}

Description:
  • Return object type, try to detect any distinguished type

Source:
Parameters:
Name Type Description
value any
Returns:
Type Description
string

detected Javascript type name

(static) tzName(tz, dst) → {string}

Description:
  • Return a timezone human name if matched (EST, PDT...), tz must be in GMT-NNNN format

Source:
Parameters:
Name Type Description
tz string
dst string
Returns:
Type Description
string

(static) unescape(str) → {string}

Description:
  • Convert escaped characters into native symbols

Source:
Parameters:
Name Type Description
str string
Returns:
Type Description
string

(static) unicode2Ascii(str, typesopt) → {string}

Description:
  • Replace Unicode symbols with ASCII equivalents, types is a string with list of types of characters to replace, default is: opqs, for quotes,other,punctuations,spaces

Source:
Parameters:
Name Type Attributes Default Description
str string
types string <optional>
opqs
Returns:
Type Description
string
Description:
  • Unlink a file, no error on non-existent file, callback is optional

Source:
Parameters:
Name Type Attributes Description
name string
callback function <optional>

(static) unlinkPath(dir, callbackopt)

Description:
  • Recursively remove all files and folders in the given path, returns an error to the callback if any

Source:
Parameters:
Name Type Attributes Description
dir string
callback function <optional>

(static) unlinkPathSync(dir)

Description:
  • Recursively remove all files and folders in the given path, stops on first error

Source:
Parameters:
Name Type Description
dir string

(static) unlinkSync(name)

Description:
  • Unlink a file, no expections

Source:
Parameters:
Name Type Description
name string

(static) uuid(prefixopt) → {string}

Description:
  • Unique Id (UUID v4) without any special characters and in lower case

Source:
Parameters:
Name Type Attributes Description
prefix string <optional>

prepend with prefix

Returns:
Type Description
string

(static) watchFiles(options, fileCallback, endCallbackopt)

Description:
  • Watch files in a dir for changes and call the callback

Source:
Parameters:
Name Type Attributes Description
options object
  • root - a string with root path
  • files - a regexp to watch files individually, if omitted watch the whole dir
  • match - a regexp to watch files when using the whole dir, only for matched files the callback will be called
  • ignore - a regexp to ignore files
  • recursive - watch files in root subfolders
  • depth - how deep to look for files in case of individual files
fileCallback function

called on changes (file)

endCallback function <optional>
Example
lib.watchFiles({ root: "./", match: /\.js$/ }, (file) => {
});

(static) weekDate(year, week) → {Date}

Description:
  • Return first day of the week by ISO week number

Source:
Parameters:
Name Type Description
year int
week int
Returns:
Type Description
Date

(static) weekOfYear(date, utcopt) → {int}

Description:
  • Return an ISO week number for given date, from https://www.epochconverter.com/weeknumbers

Source:
Parameters:
Name Type Attributes Description
date string | Date
utc boolean <optional>
Returns:
Type Description
int

(static) whilst(test, iterator, callbackopt, directopt)

Description:
  • While the test function returns true keep running the iterator, call the callback at the end if specified. All functions are called via setImmediate unless the direct argument is true

Source:
Parameters:
Name Type Attributes Description
test function
iterator function
callback function <optional>
direct boolean <optional>
Example
var count = 0;
lib.whilst(
   function(data) {
       return count < 5;
   },
   function (next, data) {
       count++;
       setTimeout(next, 1000);
   },
   function (err, data) {
       console.log(err, data, count);
    });

(static) writeLines(file, lines, optionsopt, callbackopt)

Description:
  • Write given lines into a file, lines can be a string or list of strings or numbers

Source:
Parameters:
Name Type Attributes Description
file string
lines string | Array.<string>
options object <optional>
  • size - rotate if the file is larger, keep 2 files
  • ext - file ext to append on rotation, without dot, old is default, it can be in the strftime format to use date, like %w, %d, %m
  • mode - open file mode, usually a or w
  • newline - if true newlines are added for each line
callback function <optional>

(static) xmlParse()

Description:
Source:

(static) zeropad()

Description:
  • Return a string with leading zeros

Source:

(inner) onDeferCallback()

Description:
  • To be called on timeout or when explicitely called by the runCallback, it is called in the context of the message.

Source: