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:
|
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 |
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 |
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 |
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
(static) base36 :regexp
(static) base62 :regexp
(static) base64 :regexp
(static) empty :object
(static) emptylist :array
(static) noop :function
(static) rxAscii :regexp
(static) rxCamel :regexp
(static) rxDateType :regexp
(static) rxDigits :regexp
(static) rxEmail :regexp
(static) rxEmpty :regexp
(static) rxFloat :regexp
(static) rxHtml :regexp
(static) rxIpaddress :regexp
(static) rxListType :regexp
(static) rxNoDigits :regexp
(static) rxNoHtml :regexp
(static) rxNoSpecial :regexp
(static) rxNoXss :regexp
(static) rxNumber :regexp
(static) rxNumericType :regexp
(static) rxObjectType :regexp
(static) rxPhone :regexp
(static) rxSpecial :regexp
(static) rxSplit :regexp
(static) rxSymbol :regexp
(static) rxTrue :regexp
(static) rxUrl :regexp
(static) rxUuid :regexp
(static) rxVersion :regexp
(static) rxXss :regexp
(static) uriSafe :string
(static) wordBoundaries :string
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:
Async version of module:lib.execProcess
- 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:
Async/await version of module:lib.fetch, never rejects meaning no exceptions
- 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 |
|
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:
Async version of module:lib.findProcess
- 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:
Async version of module:lib.readFile
- 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:
Async version of module:lib.spawnSeries
- 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
keyspecified 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:
Async version of module:lib.spawnProcess
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
cmd |
string | ||
options |
object |
<optional> |
Returns:
| Type | Description |
|---|---|
| object |
in format { proc, err } |
(static) autoType(val) → {string}
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}
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 filenamethe 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 theoptionsor inside themodulesas@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.regionorinstance.tag, all modules will be checked insideoptions.modulesobject 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.isTruefor matching so checking an item in an array will work as well. The [global] section can appear anytime to return to global mode- The format is:
- 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
|
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
__deferIdproperty which will be used for keeping track of the responses or it will be generated. A timeout is created for this message, ifrunCallbackfor 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 |
|
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 |
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()
(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
directargument 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:
Same as module:lib.parallel but all functions will be called and any error will be ignored
- 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> |
|
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 |
|
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:
Async version of module:lib.findFileSync, same options as in the sync version, the starting dir is not included
- 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> |
|
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
|
||||||||
callback |
function | in format (err, list) where list is { pid, cmd } |
(static) findWords()
- Description:
Return an array of
words`` found in the giventext`` separated by delimiters, this a brute force search for every keyword and usinglib.isWordto 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 returnsnullor 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 inoptions.intervalms 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 thenext()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
limitat 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 |
Properties updated and returned in the options:
|
|
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
|
(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}
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}
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
|
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:
|
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}
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}
Parameters:
| Name | Type | Description |
|---|---|---|
val |
any |
Returns:
| Type | Description |
|---|---|
| boolean |
true if the given date is valid |
(static) isEmpty(val) → {boolean}
Parameters:
| Name | Type | Description |
|---|---|---|
val |
any |
Returns:
| Type | Description |
|---|---|
| boolean |
true of the given value considered empty |
(static) isFlag(list, item) → {boolean}
Parameters:
| Name | Type | Description |
|---|---|---|
list |
Array.<any> | |
item |
any | Array.<any> |
Returns:
| Type | Description |
|---|---|
| boolean |
true if |
(static) isFunc(func) → {function|undefined}
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
objmust match all properties in the objectcondition, for comparisonlib.isTrueis used for each property in the condition object.
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
obj |
object | ||
condition |
object |
|
|
options |
object |
<optional> |
The options can provide specific |
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}
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)
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}
Parameters:
| Name | Type | Description |
|---|---|---|
val |
any |
Returns:
| Type | Description |
|---|---|
| object | undefined |
itself if a regular object and not null |
(static) isPositive(val) → {boolean}
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}
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}
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
|
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 condtioncond`.
- 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}
Parameters:
| Name | Type | Description |
|---|---|---|
str |
string |
Returns:
| Type | Description |
|---|---|
| string | undefined |
the string iself if contains Unicode characters |
(static) isUuid(str) → {string|undefined}
Parameters:
| Name | Type | Description |
|---|---|---|
str |
any |
Returns:
| Type | Description |
|---|---|
| string | undefined |
the value represents an UUID |
(static) isValidBool(…args) → {boolean}
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}
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}
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)
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}
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 |
(static) jsonFormat(obj, optionsopt)
- Description:
Nicely format an object with indentations, optional
indentlevelcan 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
|
(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
|
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 |
(static) loadLocale(file, callbackopt)
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 unlessall` 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 |
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.countor 25 first items, for objects it will show up to theoptions.keysor 25 first properties, strings are limited byoptions.lengthor 256 bytes, if truncated the full string length is shown. the object depth is limited byoptions.depthor 5 levels deep, the number of properties are limited by options.count or 15, all properties that matchoptions.ignorewill be skipped from the output, ifoptions.allowis a regexp, only properties that match it will be output. Useoptions.replacefor 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:
|
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> |
|
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:
|
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
resultargument. It useslib.objSetso 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
valoverride existing properties in theobj, returns a new object
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
obj |
object | |
options |
object |
|
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
objIncrbut 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> |
|
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> |
|
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
|
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
directargument 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.separatorcharacter(s) and surrounded by characters inoptions.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
|
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:
Same as module:lib.readFileSync but asynchronous
- 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> |
|
Returns:
| Type | Description |
|---|---|
| string | Buffer |
(static) replaceRegexp(str, rx, val) → {string}
- Description:
Safe version of replace for strings, always returns a string, if
valis 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
deferCallbackmethod. The message must have__deferIdproperty 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
deferCallbackand 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
directargument 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
|
(static) shuffle(list) → {Array.<any>}
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}
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
|
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
namemust 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
|
||||||||
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 |
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
|
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> |
|
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
|
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
|
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
invalidparameter is given, in this case invalid date returned as null. Ifdfltis 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
|
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
|
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 |
|
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 |
|
||||||||||||||||||||||||||
data |
object | Array.<object> | |||||||||||||||||||||||||||
options |
object |
<optional> |
Properties
|
(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
|
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
durationand 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
|
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
|
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
|
(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
|
||||||||||||||||||||||||||||
|
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
keyarray,op==dfor decrypt, other is encryptbased 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
- default only:
- 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
|
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
|
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> |
|
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}
Parameters:
| Name | Type | Attributes | Description | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
path |
string | module path |
|||||||||||||
options |
object |
<optional> |
Properties
|
Returns:
| Type | Description |
|---|---|
| object | undefined |
(static) typeName(value) → {string}
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 |
(static) unlink(name, callbackopt)
- 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 |
|
|
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
directargument 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> |
|
callback |
function |
<optional> |
(static) xmlParse()
- Description:
Same arguments as for module:lib.jsonParse
- Source:
(static) zeropad()
- Description:
Return a string with leading zeros
- Source: