module:lib
- Description:
General purpose utilities
- Source:
Type Definitions
ValidateOptions
- Description:
An object to be used with module:lib.validate for object validation against a schema and converting to a desired type
- Type:
- object
- 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 @..@ placeholders refering properties from the field object, the final message will be processed by module:lib.toTemplate. Any properties listed here can be used like @label@, @max@, @maxdate||date@ |
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 |
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 |
base64 |
boolean |
<optional> |
decode from base64 for json and text 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, options is passed |
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 instead of the internal property name, if not set the name is used. |
datatype |
boolean |
<optional> |
convert each value or item into this type, used by string/list types |
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 |
Members
(static) als :AsyncLocalStorage
- Description:
async storage to use with tryCatch, emits "error" signal if store has emit method
- Source:
(static) base32 :regexp
- Description:
base32 characters
- Source:
- Default Value:
- ABCDEFGHIJKLMNOPQRSTUVWXYZ234567
(static) base36 :regexp
- Description:
base36 characters
- Source:
- Default Value:
- 0123456789abcdefghijklmnopqrstuvwxyz
(static) base62 :regexp
- Description:
base62 characters
- Source:
- Default Value:
- 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
(static) base64 :regexp
- Description:
base64 characters
- Source:
- Default Value:
- ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
(static) empty :object
- Description:
empty object, frozen
- Source:
(static) emptylist :array
- Description:
empty array, frozen
- Source:
(static) isDigit :function()
- Description:
return true if an argument is a digit
- Source:
(static) noop :function()
- Description:
empty function to be used when callback was no provided
- Source:
(static) rxAscii :regexp
- Description:
ascii charset validation
- Source:
- Default Value:
- /^[\x20-\x7F]+$/
(static) rxCamel :regexp
- Description:
characters for camelizing
- Source:
- Default Value:
- /(?:[_.:-])(\w)/g
(static) rxDateType :regexp
- Description:
date and time column types
- Source:
- Default Value:
- /^(date|m?time)/i
(static) rxDigits :regexp
- Description:
digits only
- Source:
- Default Value:
- /^[0-9]+$/
(static) rxEmail :regexp
- Description:
email validation
- Source:
- Default Value:
- /^[A-Z0-9'._+-]+@[A-Z0-9.-]+\.[A-Z]{2,16}$/i
(static) rxEmpty :regexp
- Description:
empty or spaces only
- Source:
- Default Value:
- /^\s*$/
(static) rxFloat :regexp
- Description:
float number validation
- Source:
- Default Value:
- /^(-|\+)?([0-9]+)?\.[0-9]+$/
(static) rxHtml :regexp
- Description:
html brackets
- Source:
- Default Value:
- /[<>]/g
(static) rxIpaddress :regexp
- Description:
IP address validation
- Source:
- Default Value:
- /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}(\/[0-9]{1,2})?$/
(static) rxListType :regexp
- Description:
list and sets column types
- Source:
- Default Value:
- /^(list|set)$/i
(static) rxNoAscii :regexp
- Description:
all non-ascii characters
- Source:
- Default Value:
- /[^\x20-\x7F]+/g
(static) rxNoDigits :regexp
- Description:
no digits
- Source:
- Default Value:
- /[^0-9]/g
(static) rxNoHtml :regexp
- Description:
exclude html brackets
- Source:
- Default Value:
- /[^<>]/g
(static) rxNoPrintable :regexp
- Description:
all non-printable ascii/ext charset validation
- Source:
- Default Value:
- /[^\x20-\x7e\x80-\xff]+/g
(static) rxNoSpecial :regexp
- Description:
exclude punctuation and other special ASCII characters but not
: @ $ % - = , . /
- Source:
- Default Value:
- /[^~!#^&()*{}[\]"'?<>|\\]/g
(static) rxNoSymbol :regexp
- Description:
all non-symbol ASCII characters
- Source:
- Default Value:
- /[^a-z0-9_]+/gi
(static) rxNoXss :regexp
- Description:
exclude XSS characters
- Source:
- Default Value:
- /[^<>"'&%\\]/g
(static) rxNumber :regexp
- Description:
number validation
- Source:
- Default Value:
- /^(-|\+)?([0-9]+|[0-9]+\.[0-9]+)$/
(static) rxNumericType :regexp
- Description:
numeric column types
- Source:
- Default Value:
- /^(int|smallint|long|bigint|real|float|double|numeric|number|decimal|now|clock|mtime|ttl|timeout|random|counter)/i
(static) rxObjectType :regexp
- Description:
object column types
- Source:
- Default Value:
- /^(obj|object|array)$/i
(static) rxPhone :regexp
- Description:
phonre validation
- Source:
- Default Value:
- /^([0-9 .+()-]+)/
(static) rxPrintable :regexp
- Description:
printable ascii/ext charset validation
- Source:
- Default Value:
- /^[\x20-\x7e\x80-\xff]+$/
(static) rxSanitizePath :regexp
- Description:
exclude control characters and dots from the path
- Source:
- Default Value:
- /([%:\\\x00-\x1F\x7F])|((?:^|[\\/])\.\.(?:[\\/]|$))/g
(static) rxSpecial :regexp
- Description:
punctuation and other special ASCII characters but not
: @ $ % - = , . /
- Source:
- Default Value:
- /[~!#^&()*{}[\]"'?<>|\\]/g
(static) rxSplit :regexp
- Description:
list split characters
- Source:
- Default Value:
- /[,|]/
(static) rxSymbol :regexp
- Description:
symbol name validation, only alpha numeric and underscore
- Source:
- Default Value:
- /^[a-z0-9_]+$/i
(static) rxTrue :regexp
- Description:
true validation
- Source:
- Default Value:
- /^(true|on|yes|1|t)$/i
(static) rxUrl :regexp
- Description:
url validation
- Source:
- Default Value:
- /^https?:\/\/.+/
(static) rxUuid :regexp
- Description:
uuid validation
- Source:
- Default Value:
- /^([0-9a-z]{1,5}_)?[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i
(static) rxVersion :regexp
- Description:
version validation
- Source:
- Default Value:
- /^([<>=]+)? *([0-9.:]+)$|^([0-9.:]+) *- *([0-9.:]+)$/
(static) rxXss :regexp
- Description:
XSS characters
- Source:
- Default Value:
- /[<>"'&%\\]/g
(static) uriSafe :string
- Description:
characters allowed in urls
- Source:
- Default Value:
- ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._~-
(static) wordBoundaries :string
- Description:
word boundaries characters
- Source:
Methods
(static) AhoCorasick(keywords)
- Description:
Text search using Aho-Corasick algorithm, based on https://github.com/BrunoRB/ahocorasick
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
keywords |
string | searchable keywords |
(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) acheckSecret() → {Object}
- Description:
Async version of module:lib.checkSecret
- Source:
Returns:
| Type | Description |
|---|---|
| {err:object, ok:boolean} |
(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(url, optionsopt) → {object}
- Description:
Async/await version of module:lib.fetch, never rejects meaning no exceptions
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
url |
string | can be full URL or an object with parts of the url, same format as in url.format |
|
options |
object | FetchRequest |
<optional> |
customize request with input options |
Returns:
| Type | Description |
|---|---|
| object |
|
Example
const { ok, err, data } = await lib.afetch("http://api.host.com/file.txt");
const { status, 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, status, request } = await lib.afetch({ url: "http://api.host.com/user/123", method: "PUT", body: { name: "myname" } });
const { err } = = await lib.afetch("http://127.0.0.1:8000/upload", {
multipart: [ { name: "file", file: "files2.txt", data: Buffer.from("....") } ]
});
(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) aprepareSecret() → {Object}
- Description:
Async version of module:lib.prepareSecret
- Source:
Returns:
| Type | Description |
|---|---|
| {err:object, secret:string} |
(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 |
(static) arrayUpdate(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> |
Examples
// Add flags, avoiding duplicates
const flags = ["admin"];
lib.arrayUpdate("add", flags, ["active", "admin"]);
// flags => ["admin", "active"]
// Update flags: add new ones and remove names prefixed with "-"
const flags = ["admin", "active"];
lib.arrayUpdate("update", flags, ["verified", "-active"]);
// flags => ["admin", "verified"]
// Filter flags
lib.arrayUpdate("present", ["admin", "active", "verified"], ["admin", "verified"]);
// => ["admin", "verified"]
lib.arrayUpdate("absent", ["admin", "active", "verified"], ["active"]);
// => ["admin", "verified"]
(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}
- Description:
Detect type from the value
- boolean: native or strings: boolean, true, false
- regexp: string inf the format: ^...$
- json: string in the format: [..] or {..}
- list: ends with , or contains |
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
val |
any |
Returns:
| Type | Description |
|---|---|
| string |
detected library type name |
Example
lib.autoType("123");
// => "number"
lib.autoType("true");
// => "bool"
lib.autoType("^test$");
// => "regexp"
lib.autoType('{"id":1}');
// => "js"
lib.autoType("read|write|delete");
// => "list"
(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 |
Example
lib.base64ToJson("eyJhIjoxfQ==")
// { a: 1 }
lib.base64ToJson("123")
// 123
(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) clone(obj, …argsopt) → {object}
- Description:
A shallow copy of an object, still 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.clone(a, { "3": 3, "4": 4 })
b.a.push(3)
a.a.length != b.length
(static) configParse(data, optionsopt) → {Array.<string>}
- Description:
Parse data as config format name=value per line
Including other files:
- 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 theoptions.
Section with filters:
- The format is:
[name=value,...]or[name!=value,...]or [name=] 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 passed like
instance.tag
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 the 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> |
Properties
|
Returns:
| Type | Description |
|---|---|
| Array.<string> |
an array of config keys and values as [-key1, val1, -key2, val2,...] |
Example
include bkjs-@tag@.conf
[tag=service]
[role=worker]
[roles=dev,role2]
[roles=production]
[instance.tag=ec2]
[instance.roles=dev]
[env.NAME=V]
(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 |
Example
lib.decodeURIComponent("a%20b%21")
// "a b!"
lib.decodeURIComponent("%")
// ""
(static) decrypt(key, data, optionsopt) → {string}
- Description:
Decrypt data with the given key, AES-GCM-256 mode is default
- Source:
Parameters:
| Name | Type | Attributes | Description | |||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
key |
string | Buffer | |||||||||||||||||
data |
string | Buffer | |||||||||||||||||
options |
object |
<optional> |
see module:lib.encrypt for more properties Properties
|
Returns:
| Type | Description |
|---|---|
| string |
(static) deferCallback(msg, callback, timeoutopt) → {number|undefined}
- Description:
Register the callback to be run later for the given message, after registering the callback the
msgobject will have the__deferIdproperty which will be used for keeping track of the responses.The reason this property is used for tracking because the message can be send over the wire or IPC socket to other process.
A timeout is created for this message, if
runCallbackfor 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 |
|---|---|---|---|
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. NOTE: this must be a function, not closure due to binding context |
|
timeout |
int |
<optional> |
if non-zero the callback will be called if no response is received after this amount of time in ms |
Returns:
| Type | Description |
|---|---|
| number | undefined |
a deferId generated for the message or undefined if not registered |
(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
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, charsetopt) → {string}
- Description:
Encode with additional symbols, convert these into percent encoded by default: ! -> %21, * -> %2A, ' -> %27, ( -> %28, ) -> %29
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
str |
string | ||
charset |
RegExp |
<optional> |
alternative charset to percent encode |
Returns:
| Type | Description |
|---|---|
| string |
Example
lib.encodeURIComponent("a b!")
// "a%20b%21"
lib.encodeURIComponent("a*b", /[*]/g)
// "a%2Ab"
(static) encrypt(key, data, optionsopt) → {string|Buffer}
- Description:
Encrypts data using AES-GCM-256 (or specified algorithm) with optional configuration.
Uses PBKDF2 for key derivation and generates a unique initialization vector (IV) for each encryption.
Note: Error handling logs the error but returns an empty string (
''). In production environments, ensure proper error handling in the calling code.
- Source:
Parameters:
| Name | Type | Attributes | Description | ||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
key |
string | Buffer | The encryption key, can be plain text or Buffer. |
|||||||||||||||||||||||||||||||||||||||||
data |
string | Buffer | Input data to encrypt. |
|||||||||||||||||||||||||||||||||||||||||
options |
Object |
<optional> |
Optional configuration. Properties
|
Returns:
| Type | Description |
|---|---|
| string | Buffer |
|
Examples
const key = 'someSecretKey';
const plaintext = 'sensitiveData';
// Return Base64
const encrypted = lib.encrypt(key, plaintext);
const ciphertextBuffer = lib.encrypt(key, data, { encode: 'binary' });
// Custom algorithm & tag length
const encryptedCustom = lib.encrypt(key, data, { algorithm: 'aes-128-gcm', tag_length: 12 });
(static) entityToText(str) → {string}
- Description:
Convert html entities into their original symbols
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
str |
string |
Returns:
| Type | Description |
|---|---|
| string |
Example
lib.entityToText("<b>Tom & Jerry</b>")
// "<b>Tom & Jerry</b>"
lib.entityToText("AB")
// "AB"
(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 |
Example
lib.escapeUnicode("hello")
// "hello"
lib.escapeUnicode("привет")
// "\\u043f\\u0440\\u0438\\u0432\\u0435\\u0442"
(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, all fatal errors are logged
- Source:
Parameters:
| Name | Type | Attributes | Description | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
cmd |
string | ||||||||||
options |
object |
<optional> |
see Properties
|
||||||||
callback |
function() |
<optional> |
(err, stdout, stderr) |
Example
lib.execProcess("ls -ls", lib.log)
(static) extend(obj) → {object}
- Description:
Extend the object with properties similar to Object.assign but perform deep merge
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
obj |
object | |
...args |
Array.<object> |
Returns:
| Type | Description |
|---|---|
| object |
Example
lib.extend({ a:1, c:5 }, { c: { b: 2 }, d: [{ d: 3 }] }, { c: { a: 2 }})
{ a: 1, c: { b: 2, a: 2 }, d: [ { d: 3 } ] }
(static) fetch(urlopt, optionsopt, callbackopt) → {object}
- Description:
Make requests using HTTP(S) and pass it to the callback if provided
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
url |
string |
<optional> |
full URL for request |
options |
object | FetchRequest |
<optional> |
request options or existing FetchRequest to reuse, see module:lib.FetchRequest, either url or options must be provided or both, the url takes precedence over options.url |
callback |
function() |
<optional> |
callback as (err, request) where request is a {FetchRequest} object combined with input options and updated fields |
Returns:
| Type | Description |
|---|---|
| object |
|
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(words, text, delimitersopt)
- 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:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
words |
Array.<string> | ||
text |
string | ||
delimiters |
string |
<optional> |
(static) flatten(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.flatten({ a: { c: 1 }, b: { d: 1 } } )
{ 'a.c': 1, 'b.d': 1 }
> lib.flatten({ 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) 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
|
Example
lib.fromBase32("NBSWY3DP").toString()
// "hello"
lib.fromBase32("NBUQ").toString()
// "hi"
(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 |
Example
lib.fromBase62("Z")
// 61
lib.fromBase62("100")
// 3844
(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 |
Example
lib.fromBase64url("aGVsbG8_")
// "hello?"
lib.fromBase64url("dGVzdA==", true)
// Buffer containing "test"
(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
|
Returns:
| Type | Description |
|---|---|
| string |
hashids instance |
Examples
// Create a hashid instance using default configuration
const hashids = lib.getHashid();
const id = hashids.encode(123);
const value = hashids.decode(id);
// Create a hashid with a custom salt
const hashids = lib.getHashid({
salt: "my-secret-salt"
});
const id = hashids.encode(12345);
// Create hashids with a minimum length
const hashids = lib.getHashid({
min: 8
});
const id = hashids.encode(42);
// Example result: "a1B2c3D4"
// Use a custom alphabet
const hashids = lib.getHashid({
alphabet: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
});
const id = hashids.encode(999);
// Use custom separator characters
const hashids = lib.getHashid({
salt: "api",
min: 10,
separators: "cfhistuCFHISTU"
});
const id = hashids.encode(1001);
// Limit the internal counter and wrap it back to 1
const hashids = lib.getHashid({
counter: 100
});
const id = hashids.encode(55);
(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|Buffer}
- Description:
Hash wrapper without exceptions for node crypto createHash
- Source:
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
data |
string | Buffer | data to hash |
||
algorithm |
string |
<optional> |
sha256
|
any supported hash algorithm by node:crypto |
encode |
string |
<optional> |
base64
|
output encoding, use "binary" to return Buffer |
Returns:
| Type | Description |
|---|---|
| string | Buffer |
calculated hash or empty string on error |
Examples
// Create SHA-256 hash encoded as base64
const value = lib.hash("hello");
// => "LPJNul+wow4m6DsqxbninhsWHlwfp0JecwQzYpOLmCQ="
// Create SHA-256 hash encoded as hex
const value = lib.hash("hello", "sha256", "hex");
// => "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
// Create MD5 hash encoded as hex
const value = lib.hash("hello", "md5", "hex");
// => "5d41402abc4b2a76b9719d911017c592"
// Hash a Buffer
const value = lib.hash(Buffer.from("hello"), "sha256", "base64");
// => "LPJNul+wow4m6DsqxbninhsWHlwfp0JecwQzYpOLmCQ="
// Return raw Buffer by using "binary"
const value = lib.hash("hello", "sha256", "binary");
// => <Buffer 2c f2 4d ba 5f b0 a3 0e ...>
// Invalid algorithm returns an empty string
const value = lib.hash("hello", "invalid-algorithm", "hex");
// => ""
(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) includes(list, item) → {boolean}
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
list |
Array.<any> | |
item |
any | Array.<any> |
Returns:
| Type | Description |
|---|---|
| boolean |
true if |
Example
// Returns true when the item exists in the list
lib.includes(["read", "write", "delete"], "write");
// => true
// Returns false when the item does not exist in the list
lib.includes(["read", "write", "delete"], "admin");
// => false
// Search is case sensitive
lib.includes(["Read", "Write"], "read");
// => false
// Returns true when any item from the array exists in the list
lib.includes(["read", "write", "delete"], ["admin", "write"]);
// => true
// Returns false when none of the array items exist in the list
lib.includes(["read", "write", "delete"], ["admin", "owner"]);
// => false
// Returns false when the first argument is not an array
lib.includes(null, "read");
// => false
// Scalar falsy values are not matched
lib.includes([0, false, ""], 0);
// => false
// Falsy values inside an item array can still be matched
lib.includes([0, false, ""], [0]);
// => true
(static) inspect(obj, optionsopt) → {string}
- Description:
Convert an object structure to a string with simplified format, used for logging
- Source:
Parameters:
| Name | Type | Attributes | Description | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
obj |
object | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
options |
objects |
<optional> |
Properties
|
Returns:
| Type | Description |
|---|---|
| string |
Example
> lib.inspect({ a: 1, b: { c: 2 }, s: "test" })
'a: 1, b: {c: 2}, s: test'
> lib.inspect(process.features)
'inspector: true, debug: false, uv: true, ipv6: true, tls_alpn: true, tls_sni: true, tls_ocsp: true, tls: true, openssl_is_boringssl: false'
(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, dfltopt) → {Array.<any>|undefined}
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
val |
Array.<any> | ||
dflt |
any |
<optional> |
default value if not valid |
Returns:
| Type | Description |
|---|---|
| Array.<any> | undefined |
the array if the value is non empty array or dflt value if given or undefined |
Example
lib.isArray([1, 2, 3]);
// => [1, 2, 3]
lib.isArray([]);
// => undefined
lib.isArray([], ["default"]);
// => ["default"]
lib.isArray("test");
// => 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, dfltopt) → {Date|undefined}
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
val |
any | ||
dflt |
any |
<optional> |
default value if not valid |
Returns:
| Type | Description |
|---|---|
| Date | undefined |
true the date itself if valid or undefined |
Example
lib.isDate(new Date());
// => true
lib.isDate(new Date("2024-01-01"));
// => true
lib.isDate(new Date("bad-date"));
// => false
lib.isDate("2024-01-01");
// => false
(static) isEmpty(val) → {boolean}
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
val |
any |
Returns:
| Type | Description |
|---|---|
| boolean |
true of the given value considered empty |
Example
lib.isEmpty(null);
// => true
lib.isEmpty("");
// => true
lib.isEmpty([]);
// => true
lib.isEmpty({});
// => true
lib.isEmpty({ id: 1 });
// => false
(static) isFunc(func, dfltopt) → {function|undefined}
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
func |
string | ||
dflt |
any |
<optional> |
default value if not valid function |
Returns:
| Type | Description |
|---|---|
| function() | undefined |
the function itself or undefined if not a function |
Example
function test() {}
lib.isFunc(test);
// => test
lib.isFunc(() => true);
// => [Function]
lib.isFunc("test");
// => undefined
lib.isFunc(null);
// => undefined
(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, dflt) → {number|NaN}
- Source:
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
val |
any | ||
dflt |
any |
NaN
|
default value if not valid |
Returns:
| Type | Description |
|---|---|
| number | NaN |
itself if the value is a valid number or NaN |
Example
lib.isNumber(123);
// => 123
lib.isNumber(0);
// => 0
Number.isNaN(lib.isNumber("123"));
// => true
Number.isNaN(lib.isNumber(NaN));
// => true
(static) isNumeric(val)
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
val |
any | Return {boolean} true if the value is a number or string representing a number |
Example
lib.isNumeric(123);
// => true
lib.isNumeric("123");
// => true
lib.isNumeric("-12.5");
// => true
lib.isNumeric("abc");
// => false
lib.isNumeric(null);
// => false
(static) isObject(val, dfltopt) → {object|undefined}
- Description:
Detect if the input is valid object and return it, while the function starts with
isand may mean it returns a boolean this way is more practival and does check and return in one call.
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
val |
any | ||
dflt |
any |
<optional> |
default value if not valid |
Returns:
| Type | Description |
|---|---|
| object | undefined |
itself if a regular object and not null or undefined |
Example
lib.isObject({ id: 1 });
// => { id: 1 }
lib.isObject(null);
// => undefined
lib.isObject([1, 2, 3]);
// => undefined
lib.isObject(new Date());
// => undefined
(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 |
Example
lib.isPositive(10);
// => true
lib.isPositive(0);
// => false
lib.isPositive(-5);
// => false
lib.isPositive("10");
// => false
(static) isPrefixed(val, prefix) → {boolean}
- Description:
Check if the value is prefixed with given prefix
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
val |
any | |
prefix |
string |
Returns:
| Type | Description |
|---|---|
| boolean |
Example
lib.isPrefixed("user:123", "user:");
// => true
lib.isPrefixed("admin:123", "user:");
// => false
lib.isPrefixed(123, "user:");
// => false
lib.isPrefixed("user:123", null);
// => false
(static) isRegExp(rx, dfltopt) → {RegExp|undefined}
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
rx |
RegExp | ||
dflt |
any |
<optional> |
default value if not valid |
Returns:
| Type | Description |
|---|---|
| RegExp | undefined |
the regexp itself or undefined if not a valid RegExp |
Example
lib.isRegExp(/^test$/);
// => /^test$/
lib.isRegExp("test");
// => undefined
lib.isRegExp("test", /default/);
// => /default/
lib.isRegExp(new RegExp("abc"));
// => /abc/
(static) isSimilar(s1, s2, optionsopt)
- Description:
Returns a score between 0 and 1 for two strings, 0 means no similarity, 1 means exactly similar. The default algorithm is Cosine Similarity, options.type can be used to specify a different algorithm:
- Source:
Parameters:
| Name | Type | Attributes | Description | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
s1 |
string | ||||||||||
s2 |
string | ||||||||||
options |
object |
<optional> |
Properties
|
Example
lib.isSimilar("test", "test");
// => 1
lib.isSimilar("", "test");
// => 0
lib.isSimilar("martha", "marhta");
// => 0.9611111111111111
lib.isSimilar("night", "nacht", { type: "sd" });
// => 0.25
lib.isSimilar("hello world", "hello there", { type: "cs" });
// => 0.4999999999999999
(static) isString(val, dfltopt) → {string|any}
- Source:
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
val |
string | |||
dflt |
any |
<optional> |
""
|
default value if not valid |
Returns:
| Type | Description |
|---|---|
| string | any |
the string value or empty string if not a string |
Example
lib.isString("hello");
// => "hello"
lib.isString("");
// => ""
lib.isString(123);
// => ""
lib.isString(null);
// => ""
(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`.For typed values strict equality is used, === but for untyped values default != is used relying on Javascript type coersion
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
val |
any | ||
condition |
object | ||
op |
string |
<optional> |
|
type |
string |
<optional> |
Returns:
| Type | Description |
|---|---|
| boolean |
true if equal |
Example
lib.isTrue("5", 5);
// => true
lib.isTrue(10, 5, "gt", "number");
// => true
lib.isTrue(7, "5,10", "between", "number");
// => true
lib.isTrue("admin", "user,admin", "in");
// => true
lib.isTrue("hello", /^h/);
// => true
(static) isUnicode(str, dfltopt) → {string|undefined}
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
str |
string | ||
dflt |
any |
<optional> |
default value if not valid |
Returns:
| Type | Description |
|---|---|
| string | undefined |
the string iself if contains Unicode characters |
Example
lib.isUnicode("café");
// => "café"
lib.isUnicode("hello");
// => undefined
lib.isUnicode("Привет");
// => "Привет"
lib.isUnicode("hello 😀");
// => "hello 😀"
(static) isUuid(str) → {string|undefined}
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
str |
any |
Returns:
| Type | Description |
|---|---|
| string | undefined |
the value represents an UUID if valid |
Example
lib.isUuid("550e8400-e29b-41d4-a716-446655440000");
// => "550e8400-e29b-41d4-a716-446655440000"
lib.isUuid("not-a-uuid");
// => undefined
lib.isUuid("550e8400-e29b-41d4-a716-446655440000", "550e");
// => "550e8400-e29b-41d4-a716-446655440000"
lib.isUuid("550e8400-e29b-41d4-a716-446655440000", "abc");
// => undefined
(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 |
Example
lib.isWord("hello world", 0, 4);
// => true
lib.isWord("hello world", 1, 4);
// => false
lib.isWord("hello world", 6, 10);
// => true
lib.isWord("foo_bar", 4, 6, "_");
// => true
(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
|
Examples
lib.jsonFormatPreset("plain", { quote1: "", quote2: "", squote1: "", squote2: "" })
// registers or updates the "plain" preset
lib.jsonFormat({ a: "test" }, { preset: "plain" })
// "{\na: test\n}"
lib.jsonFormat({ a: 1, b: true })
// "{\n \"a\": 1, \n \"b\": true\n}"
lib.jsonFormat({ a: [1, 2] }, { preset: "compact" })
// yaml-like compact text
lib.jsonFormat('{"a":1}')
// pretty formatted object string
lib.jsonFormat({ password: "secret" }, { hide: /password/ })
// hides matched values
(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 |
Example
lib.jsonToBase64({ a: 1 })
// "eyJhIjoxfQ=="
lib.jsonToBase64([1, 2, 3])
// "WzEsMiwzXQ=="
(static) killWorkers(filter)
- Description:
Kill all workers
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
filter |
string | number | object |
(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) lzCompress(data, encodingopt)
- Description:
From https://github.com/pieroxy/lz-string/
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
data |
string | ||
encoding |
string |
<optional> |
base64, utf16 |
(static) lzDecompress(data, encodingopt)
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
data |
string | ||
encoding |
string |
<optional> |
base64, utf16 |
(static) makePath(dir, callbackopt)
- Description:
Async version of makePath, stops on first error, EEXIST is ignored
- 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) 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) 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 and dynamically when optional chanining cannot be used.
- 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
|
Example
var a = {}
lib.objIncr(a, "a", 1)
lib.objIncr(a, "b", 10)
a
{ a: 1, b: 10 }
(static) objKeys(obj) → {Array.<string>}
- Description:
Return all property names for an object or empty if not an object
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
obj |
object |
Returns:
| Type | Description |
|---|---|
| Array.<string> |
(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) 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)
// { item: { count: 1 } }
lib.objSet(a, "response.item.count", 1, { incr: 1 })
// { item: { count: 2 } }
(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> |
Example
// 24-hour format with minutes
lib.parseTime("14:30"); // [14, 30]
// 24-hour format, hour only
lib.parseTime("14"); // [14, 0]
// 12-hour format with am/pm (case-insensitive)
lib.parseTime("9:30am"); // [9, 30]
lib.parseTime("9:30PM"); // [21, 30]
// 12am is midnight, 12pm is noon
lib.parseTime("12:00am"); // [0, 0]
lib.parseTime("12:00pm"); // [12, 0]
// Surrounding whitespace is trimmed
lib.parseTime(" 07:15 "); // [7, 15]
// Non-string input is coerced via String()
lib.parseTime(830); // ["830" doesn't match 0-23] -> undefined
lib.parseTime("8:30"); // [8, 30]
// Invalid formats return undefined
lib.parseTime("25:00"); // undefined (hour out of range)
lib.parseTime("14:60"); // undefined (minute out of range)
lib.parseTime("abc"); // undefined
lib.parseTime("1:2:3"); // undefined
(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> |
Properties
|
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(msg)
- 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:
Parameters:
| Name | Type | Description |
|---|---|---|
msg |
object | the message with __deferId key |
(static) sanitizePath(…args) → {string}
- Description:
Removes invalid characters
..and% : \ \x0 - \x1F, \x7Fto eliminate traversal errors but may result in completely non-existent path or empty string.First arg is assumed but not enforced to be the root and trusted and resolved to the absolute path beforehand.
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
args |
...any |
<repeatable> |
concat all parts using path.join after sanitizing each part, non-strings are ignored |
Returns:
| Type | Description |
|---|---|
| string |
sanitized and normalized path or empty string |
Example
> lib.sanitizePath("/usr/www/root", "../%2e%2e//../etc/......./\r\necho/./pas\1swd\00.0\x00.exe")
'/usr/www/root/2e2e/etc/......./echo/passwd.0.exe'
(static) sanitizePath(…args) → {string|undefined}
- Description:
Validate very strictly given paths for invalid characters
..and% : \ \x0 - \x1F, \x7F, return undefined on any invalid character or non-string, if all good join and normalize.
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
args |
...string |
<repeatable> |
concat all parts using path.join after checking each part |
Returns:
| Type | Description |
|---|---|
| string | undefined |
validated normalied path or undefined on error |
Example
> lib.validatePath("/usr/www/root", "../%2e%2e//../etc/......./\r\necho/./pas\1swd\00.0\x00.exe")
undefined
> lib.validatePath("/usr/www/root", "my/file.txt")
`/usr/www/root/my/file.txt`
(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
|
Example
// Generate a SnowFlake-style id as a decimal string
const id = lib.sfuuid();
// "7138729462243536896"
// Generate an id for a specific node
const nodeId = lib.sfuuid({ node: 42 });
// "7138729462243710976"
// Generate an id with a fixed timestamp, useful for tests
const testId = lib.sfuuid({
now: 1700000000000,
node: 1,
});
// "7130316800000004096"
// Generate an id using microsecond local epoch
const microId = lib.sfuuid({ epoch: "m", node: 7 });
// Generate an id encoded in base36
const base36Id = lib.sfuuid({
node: 12,
radix: 36,
});
// "1i7m6g25x4ao"
// Generate an id encoded in hexadecimal
const hexId = lib.sfuuid({
node: 12,
radix: 16,
});
// "631f8d28000c000"
(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> |
sha256
|
|
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) 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 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 |
Array.<object> | Array.<string> | is a list of commands to execute, runs module:lib.spawnProcess for each command. |
|||||||||
options |
object |
<optional> |
commond properties for Properties
|
||||||||
callback |
function() |
<optional> |
(err, stdout, stderr) |
Example
lib.spawnSeries([
"ls -la",
"ps augx",
{ command: "du", args: "-sh", stdio: "inherit", cwd: "/tmp" },
{ command: "du", args: "-sh", stdio: "inherit", cwd: "/etc" },
"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) strftime(date, fmt, optionsopt) → {string}
- Description:
Format date object according to Unix strftime function
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
date |
string | number | Date | ||
fmt |
string | ||
options |
object |
<optional> |
Returns:
| Type | Description |
|---|---|
| string |
(static) stringify(obj, replaceropt, spaceopt, escapeopt)
- 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> |
|
escape |
boolean |
<optional> |
escape Unicode |
Example
lib.stringify({ a: 1 })
// "{\"a\":1}"
lib.stringify({ a: 1 }, null, 2)
// "{\n \"a\": 1\n}"
lib.stringify({ text: "привет" }, null, 0, true)
// "{\"text\":\"\\u043f\\u0440\\u0438\\u0432\\u0435\\u0442\"}"
(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 |
Example
// Generate a short unique id
const id = lib.suuid();
// "k9z3x"
// Generate a short unique id with a prefix
const orderId = lib.suuid("ord_");
// "ord_k9z3x"
// Generate using microsecond local epoch
const microId = lib.suuid("evt_", { epoch: "m" });
// "evt_2n9m8p"
// Generate using second local epoch
const secondId = lib.suuid("job_", { epoch: "s" });
// "job_x7q2"
// Pass hashid options supported by lib.getHashid
const customId = lib.suuid("msg_", {
epoch: "m",
salt: "my-app",
alphabet: "abcdefghijklmnopqrstuvwxyz1234567890",
});
(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 |
Example
lib.textToEntity("<b>Tom & Jerry</b>")
// "<b>Tom & Jerry</b>"
lib.textToEntity("plain")
// "plain"
(static) textToXml(str) → {string}
- Description:
Convert all special symbols into xml entities
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
str |
string |
Returns:
| Type | Description |
|---|---|
| string |
Example
lib.textToXml("<tag attr=\"1\">Tom & Jerry</tag>")
// "<tag attr="1">Tom & Jerry</tag>"
lib.textToXml("Bob's")
// "Bob's"
(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 |
Example
lib.toBase32(Buffer.from("hello"))
// "NBSWY3DP"
lib.toBase32(Buffer.from("hi"), { padding: true })
// "NBUQ===="
(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 |
Example
lib.toBase62(61)
// "Z"
lib.toBase62(3844)
// "100"
(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 |
Example
lib.toBase64url("hello?")
// "aGVsbG8_"
lib.toBase64url(Buffer.from("test"))
// "dGVzdA=="
(static) toBool(val, dfltopt) → {boolean}
- Description:
Return true if value represents true condition, i.e. non empty value including yes, ok, 1, true
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
val |
string | number | boolean | ||
dflt |
any |
<optional> |
Returns:
| Type | Description |
|---|---|
| boolean |
Example
lib.toBool("yes")
// true
lib.toBool("0")
// false
lib.toBool(undefined, "true")
// true
(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 |
Example
lib.toCamel("hello_world")
// "helloWorld"
lib.toCamel("hello-world", "-")
// "helloWorld"
(static) toCookie(name, valueopt, optionsopt) → {string}
- Description:
Serialize name/value into a string to be set in header Set-Cookie, options may contain cookie parameters according to https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Cookies
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
name |
string | ||
value |
string |
<optional> |
|
options |
string |
<optional> |
Returns:
| Type | Description |
|---|---|
| string |
Example
lib.toCookie("sid", "abc 123")
// "sid=abc%20123"
lib.toCookie("sid", "abc", { httpOnly: true, secure: true, sameSite: "Strict" })
// "sid=abc; HttpOnly; Secure; SameSite=Strict"
lib.toCookie("sid", "", { maxAge: 3600, path: "/" })
// "sid=; Max-Age=3600; Path=/"
(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 |
Example
lib.toDate("2024-01-02T03:04:05Z")
// Date object for 2024-01-02T03:04:05.000Z
lib.toDate(1704164645)
// Date object from Unix seconds
lib.toDate("bad date", null, true)
// null
(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 |
Example
lib.toDigits("+1 (555) 123-4567")
// "15551234567"
lib.toDigits("abc123def")
// "123"
(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 |
Example
lib.toDuration(65000)
// "1 minute 5 seconds"
lib.toDuration(3600000, { short: true })
// "1h"
lib.toDuration(Date.now() - 60000, { age: true, round: 1 })
// "1 minute"
(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 |
Example
lib.toEmail("User@Example.COM")
// "user@example.com"
lib.toEmail("User Name <user@example.com>", { parse: true })
// "user@example.com"
lib.toEmail("bad..email@example.com")
// ""
(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
|
Example
lib.toFormat("csv", [{ id: 1, name: "Bob" }], { header: true })
// "id,name\r\n1,Bob\r\n"
lib.toFormat("json", [{ id: 1 }])
// "{\"id\":1}\n"
lib.toFormat("xml", [{ id: 1 }])
// "<row>\n<id>1</id>\n</row>\n"
lib.toFormat("jsontext", [{ id: 1 }])
// formatted JSON text
(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 |
Example
lib.toMtime("2024-01-02T03:04:05Z")
// 1704164645000
lib.toMtime("bad date", 1000)
// 1000
(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")
123
lib.toNumber("1.23", { float: 1, dflt: 0, min: 0, max: 2 })
1.23
lib.toNumber("1.23", {float: false })
1
(static) toPercentEncoded(str, charsetopt) → {string}
- Description:
Encode as percent encoded for given set of characters
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
str |
string | ||
charset |
RegExp |
<optional> |
if empty all characters will be converted |
Returns:
| Type | Description |
|---|---|
| string |
Example
lib.toPercentEncoded("abc")
// "%61%62%63"
lib.toPercentEncoded("a b", / /g)
// "a%20b"
(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
|
Example
lib.toPrice(12.5)
// "$12.50"
lib.toPrice(12.5, { currency: "EUR", locale: "de-DE" })
// "12,50 €"
(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 |
Example
lib.toRFC3339(new Date("2024-01-02T03:04:05.006Z"))
// "2024-01-02T03:04:05.006+00:00" in UTC timezone
lib.toRFC3339()
// current local time in RFC3339 format
(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 |
Example
lib.toRegexp("hello", "i").test("HELLO")
// true
lib.toRegexp("a+b", { escape: true }).test("a+b")
// true
lib.toRegexp("[")
// undefined
(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> |
Properties
|
Returns:
| Type | Description |
|---|---|
| object |
in format { list, rx } |
Example
const obj = lib.toRegexpObj(null, "admin")
// { list: ["admin"], rx: /admin/ }
obj.rx.test("admin")
// true
lib.toRegexpObj(obj, "!admin")
// { list: [], rx: null }
(static) toSize(size, decimalsopt)
- Description:
Return size human readable format
- Source:
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
size |
number | |||
decimals |
boolean |
<optional> |
2
|
Example
lib.toSize(1024)
// "1 KBytes"
lib.toSize(1536, 1)
// "1.5 KBytes"
(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" })
'http://www.site.com/YYY/123'
lib.toTemplate("Hello @name|friend@!", {})
'Hello 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 |
Example
lib.toTitle("hello_world")
// "Hello World"
lib.toTitle("id", 2)
// "id"
(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 |
Example
lib.toUncamel("helloWorld")
// "hello-world"
lib.toUncamel("helloWorld", "_")
// "hello_world"
(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 |
Example
lib.toUrl("https://example.com/a?b=1")
// "https://example.com/a?b=1"
lib.toUrl("https://example.com", { url: true }).hostname
// "example.com"
(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 |
Examples
lib.toValue("123", "int")
// 123
lib.toValue("true", "bool")
// true
lib.toValue("a,b,c", "list")
// ["a", "b", "c"]
lib.toValue('{"a":1}', "js")
// { a: 1 }
lib.toValue("user@example.com", "email")
// "user@example.com"
lib.toString(123)
// "123"
lib.toString(null)
// ""
(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) → {string}
- Description:
Create a Timed One-Time Password, RFC6328
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
key |
string | ||
options |
object |
<optional> |
Returns:
| Type | Description |
|---|---|
| string |
(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) trim(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) 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 emptry but not a function
- 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) → {undefined|Error}
- 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. If the async local storage is not empty and has
emitmethod it will be called aserrorevent.
- 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 |
|---|---|
| undefined | Error |
|
(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|null}
- 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
|
Returns:
| Type | Description |
|---|---|
| object | null |
(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 |
Example
lib.typeName(null);
// => "null"
lib.typeName([1, 2, 3]);
// => "array"
lib.typeName(Buffer.from("test"));
// => "buffer"
lib.typeName(new Error("boom"));
// => "error"
lib.typeName({ id: 1 });
// => "object"
(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 |
Example
lib.unescape("hello\\nworld")
// "hello\nworld"
lib.unescape("\\\"quoted\\\"")
// "\"quoted\""
(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 |
Example
lib.unicode2Ascii("“hello”")
// "\"hello\""
lib.unicode2Ascii("hello\u00a0world", "s")
// "hello world"
(static) unlink(name, callbackopt)
- Description:
Unlink a file, no error on non-existent file (ENOENT is ignored), 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 |
Example
// Generate a plain UUID v4 without dashes
const id = lib.uuid();
// "9f1c7a6f4d2b4a7b9e0a43e9f5a2c1b8"
// Generate a UUID with a prefix
const userId = lib.uuid("usr_");
// "usr_9f1c7a6f4d2b4a7b9e0a43e9f5a2c1b8"
// Use it as an object key
const session = {
id: lib.uuid("sess_"),
created: Date.now(),
};
// Check the generated UUID length
lib.uuid().length;
// 32
(static) validBool(…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) validFunc(…args) → {any}
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
args |
...any |
<repeatable> |
Returns:
| Type | Description |
|---|---|
| any |
first function |
(static) validNumber(…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) validPositive(…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) validValue(…args) → {any}
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
args |
...any |
<repeatable> |
Returns:
| Type | Description |
|---|---|
| any |
first non empty value or undefined |
(static) validVersion(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) validate(query, schema, optionsopt) → {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.
This validation serves 2 purposes:
- verify error conditions for the converted fields
- convert incoming user data into desired types, means the schema is not strict in the sense that all incoming data must be of desired type, all transformations like strip/replace.... are run in the order as defined in the schema object to control order of changes
For example if we need a numeric code from a user sent, it is ok to receive it as string and convert, if there are no more conditions check we we work with the number. If there are range checks then in case of error we will notify the user or service about it.
- Source:
Parameters:
| Name | Type | Attributes | Description | ||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
query |
object | request query object, usually req.context.query or req.context.body |
|||||||||||||||||||||||||
schema |
object | an object in format: { name: module:lib.ValidateOptions, ...} |
|||||||||||||||||||||||||
options |
object |
<optional> |
options can define the following properties to customize convertion: Properties
|
Returns:
| Type | Description |
|---|---|
| {err:object, data:object} |
an object with properties:
|
Examples
User login form validation
api.app.post("/login", (context) => {
const { err, data } = api.validate(context, {
login: { type: "email", required: 1 },
password: { required: 1 },
code: { type: "int", minnum: 100000 },
});
if (err) return lib.tryCall(callback, err);
});
Show most fields at once for review purposes
const { err, data } = lib.validate(context.context.body, {
id: { type: "int" },
uid: { type: "uuid" },
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 for @label@" },
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 for @label@" },
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 },
"**" : { max: 512 }
});
if (err) return context.reply(err);
(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) wrap(str, optionsopt) → {string}
- Description:
Wrap a long string
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
str |
string | ||
options |
object |
<optional> |
|
Returns:
| Type | Description |
|---|---|
| string |
Example
# lib.wrap("very long text line to wrap forward", { wrap: 15, over: 1.5})
'very long text line\nto wrap forward'
# lib.wrap("very long text line to wrap backwards", { wrap: 15, over: 0.5 })
'very long text\nline to wrap\nbackwards'
(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:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
options.parser |
object |
<optional> |
custom options for xmlParser from "fast-xml-parser" packagge |
(static) zeropad()
- Description:
Return a string with leading zeros
- Source: