module:lib
- Description:
General purpose utilities
Type Definitions
ParamsOptions
- Description:
An object to be used with toParams for validation
Properties:
| Name | Type | Attributes | Description |
|---|---|---|---|
name |
boolean | to save a value with different name than in the original query |
|
type |
string |
<optional> |
convert the input to the type format, default text Supported types:
|
dflt |
boolean |
<optional> |
use this value if property does not exists or undefined |
dfltempty |
boolean |
<optional> |
also use the dflt value for empty properties |
required |
boolean |
<optional> |
if true the target value must not be empty, the check is performed after type conversion,
if an object it checks the target object using |
errmsg |
boolean |
<optional> |
return this error on error or invalid format or required condition, it may contain %s sprintf-like placeholders depending on the error |
min |
boolean |
<optional> |
minimum length for the target data, returns an error if smaller, for list type will skip item from the list |
max |
boolean |
<optional> |
maximum length alowed, returns an error if longer |
trunc |
boolean |
<optional> |
if true and longer than max just truncate the value instead of returning an error or skipping |
separator |
boolean |
<optional> |
for list type default separator is |
delimiter |
boolean |
<optional> |
map type contains elements separated by , by default, use another if commas are expected |
regexp |
boolean |
<optional> |
validate input against this regexp and return an error if not matched, for list type skip items not matched |
noregexp |
boolean |
<optional> |
validate the input against this regexp and return an error if matched, for list type skip items matched |
datatype |
boolean |
<optional> |
convert each value or item into this type, used by string/list types |
maptype |
boolean |
<optional> |
for maps convert each value to this type |
novalue |
boolean |
<optional> |
if the target value equals then ignore the parameter, can be a list of values to be ignored or an object { name, value }. For lists this is a number of items in the list, if less or equal the list is ignored or reset. |
ignore |
boolean |
<optional> |
if true skip this parameter |
optional |
boolean |
<optional> |
for date types, if true do not assign the current time for empty values |
value |
boolean |
<optional> |
assign this value unconditionally |
values |
boolean |
<optional> |
a list of allowed values, if not present the parameter is ignored |
values_map |
boolean |
<optional> |
an object map for values, replace matching values with a new one |
params |
boolean |
<optional> |
an object with schema to validate for json/obj/array types |
empty |
boolean |
<optional> |
if true and the target value is empty return as empty, by default empty values are ignored |
setempty |
boolean |
<optional> |
to be used with |
keepempty |
boolean |
<optional> |
for list type keep empty items in the list, default is skip empty items |
minlist |
boolean |
<optional> |
min allowed length of the target array for list/map types, returns error if less |
maxlist |
boolean |
<optional> |
max allowed length of the target array for list/map types, returns error if longer |
minnum |
boolean |
<optional> |
min allowed number after convertion by toNumber, for numbers and mtime |
maxnum |
boolean |
<optional> |
max allowed number after convertion by toNumber, for numbers and mtime |
mindate |
boolean |
<optional> |
min allowed date after convertion by toDate, can be a Date or number |
maxdate |
boolean |
<optional> |
max allowed date after convertion by toDate, can be a Date or number |
label |
boolean |
<optional> |
alternative name to use in error messages which uses sprintf-like placeholders, all min/max like errors have name as first and threshold as second arg, label can be set to use friendlier name |
strip |
boolean |
<optional> |
a regexp with characters to strip from the final value |
upper/lower |
boolean |
<optional> |
transform case |
cap |
boolean |
<optional> |
capitalize the value |
trim |
boolean |
<optional> |
trim the final value if a string |
replace |
boolean |
<optional> |
an object map with characters to be replaced with other values |
base64 |
boolean |
<optional> |
decode from base64 |
An object to be used with toParams for validation
Type:
- object
Methods
(static) __()
- Description:
Simple i18n translation method compatible with other popular modules, supports the following usage:
Example
lib.__(name)
lib.__(fmt, arg,...)
lib.__({ phrase: "", locale: "" }, arg...
(static) base64ToJson()
- 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 chnaged and was signed with the same secret
(static) call(obj, methodopt, …argsopt)
- Description:
Call a function safely with context:
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 |
Example
lib.call(func,..)
lib.call(context, func, ...)
lib.call(context, method, ...)
(static) clock()
- Description:
Returns current time in microseconds since January 1, 1970, UTC
(static) configParse(data, optionsopt) → {Array.<string>}
- Description:
Parse data as config format name=value per line
Include supports:
- The format is:
$include filenamethe contents of the given file will be included in place and parsed. File name may contain placeholders formatted as @name@ where name can refer to any property inside theoptionsor inside themodulesas@module.name@
Supports sections:
- The format is:
[name=value,...]or[name!=value,...]where name is a property name with optional value(s). - if the value is empty then it just checks if the property is empty.
!=denotes negative condition, i.e. not matching or NOT empty- section names may refer deep into objects like
aws.regionorinstance.tag, all modules will be checked insideoptions.modulesobject only, all other names are checked in the top level options.
Sections work like a filter, only if a property matches it is used otherwise skipped completely, it uses
lib.isTruefor matching so checking an item in an array will work as well. The [global] section can appear anytime to return to global mode- The format is:
Parameters:
| Name | Type | Attributes | Description | ||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
data |
string | Array.<string> | a string or array with config lines, a string will be split by newline |
|||||||||||||||||
options |
object |
<optional> |
options with context Properties
|
Returns:
| Type | Description |
|---|---|
| Array.<string> |
an array of config keys and values as [-key1, val1, -key2, val2,...] |
(static) daysInMonth()
- Description:
Return the number of days in the given month of the specified year.
(static) decodeURIComponent()
- Description:
No-exception version of the global function, on error return empty string
(static) deferCallback(parent, msg, callback, timeoutopt) → {object}
- Description:
Register the callback to be run later for the given message, the message may have the
__deferIdproperty which will be used for keeping track of the responses or it will be generated. A timeout is created for this message, ifrunCallbackfor this message will not be called in time the timeout handler will call the callback anyway with the original message.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
parent |
object | can be any object and is used to register the timer and keep reference to it, a |
|
msg |
object | the message |
|
callback |
function | will be called with only one argument which is the message itself, what is inside the message this function does not care. If any errors must be passed, use the message object for it, no other arguments are expected. |
|
timeout |
int |
<optional> |
how long to wait, if not given |
Returns:
| Type | Description |
|---|---|
| object |
an object with timer and callback |
(static) deferInterval()
- Description:
Assign or clear an interval timer by name, keep the reference in the given parent object
(static) deferShutdown()
- Description:
Clear all pending timers
(static) encodeURIComponent()
- Description:
Encode with additional symbols, convert these into percent encoded:
! -> %21, * -> %2A, ' -> %27, ( -> %28, ) -> %29
(static) entityToText()
- Description:
Convert html entities into their original symbols
(static) escapeUnicode()
- Description:
Convert all Unicode binary symbols into Javascript text representation
(static) fromBase32(str, optionsopt)
- Description:
Convert a string in base32 into a Buffer
Parameters:
| Name | Type | Attributes | Description | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
str |
string | base32 encoded string |
|||||||||
options |
object |
<optional> |
Properties
|
(static) fromBase62()
- Description:
Convert base62 number as a string into base10 number
(static) fromBase64url()
- Description:
Decode base64url into a string
(static) getArg(name, dfltopt) → {string}
- Description:
Return commandline argument value by name
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
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:
Parameters:
| Name | Type | Attributes | Description | ||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
object |
<optional> |
Properties
|
Returns:
| Type | Description |
|---|---|
| string |
hashids instance |
(static) getWorkers(filteropt, filteropt)
- Description:
Return a worker by id or list of workers, useful only in primary process only, always returns an object.
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:
|
(static) hash(data, algorithmopt, encodeopt) → {string}
- Description:
Hash wrapper without exceptions for node crypto createHash
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
data |
string | Buffer | data to hash |
|
algorithm |
string |
<optional> |
sha1 is default, any supported hash algorithm by node:crypto |
encode |
string |
<optional> |
encoding, base64 by default |
Returns:
| Type | Description |
|---|---|
| string |
calculated hash or empty string on error |
(static) 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.
Parameters:
| Name | Type | Description |
|---|---|---|
name |
string | argument name |
Returns:
| Type | Description |
|---|---|
| boolean |
(static) isDST()
- Description:
Returns true if the given date is in DST timezone
(static) isTimeRange()
- Description:
Returns 0 if the current time is not within specified valid time range or it is invalid. Only continious time rang eis support, it does not handle over the midninght ranges, i.e. time1 is always must be greater than time2.
options.tzto specify timezone, no timezone means current timezone.options.dateif given must be a list of dates in the format: YYY-MM-DD,...
(static) jsonFormat()
- Description:
Nicely format an object with indentations, optional
indentlevelcan be used to control until which level deep to use newlines for objects. Options:- preset - predefined set of options,
compactprints yaml-like text version, if a list all presets are combined - indent - initial indent, empty default
- ilevel - level to start to use spaces for indentation, 0 default
- ignore - regexp with properties to ingore
- skipnull - do not print null/undefined/""
- skipempty - skip all empty object accorsding to
lib.isEmpty - map - an object to map property names
- replace - an object for string values replacement: { ORIG: REPL... }
- preprocess - a function(name, val, options) to run before prints, return undefined to skip
- sbracket1, sbracket2 - open/close brackets for arrays, [ ]
- cbracket1, cbracket2 - open close brackets for obejcts, { }
- nl1, nl2 - newline chars before and after a single property
- quote1, quote2 - quotes for property names
- squote1, squote2 - quotes for string values
- comma - comma separator between items
- sep - separator between array items, comma by default
- space - symbol for indentation
- nspace - how many spaces to use for indentation, 4
- prefix - prefix for array items, each item on new line, requires
nl1 - wrap - wrap long strings at this length
- over - number greater than 1 to allow extra characters over wrap length
- delim - characters that trigger wrapping
- preset - predefined set of options,
(static) jsonFormatPreset()
- Description:
Register or update a jsonFormat preset
(static) jsonParse(data, optionsopt) → {object|array}
- Description:
Silent JSON parse, returns null on error, no exceptions raised.
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()
- Description:
Stringify JSON into base64 string, if secret is given, sign the data with it
(static) killWorkers(filter)
- Description:
Kill all workers
Parameters:
| Name | Type | Description |
|---|---|---|
filter |
string | number | object |
(static) loadLocale(file, callbackopt)
- Description:
Load a file with locale translations into memory
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
file |
string | ||
callback |
function |
<optional> |
(static) localEpoch()
- Description:
Returns current time in seconds (s), microseconds (m), time struct (tm) or milliseconds since the local
lib._epoch(2025-11-15 UTC)
(static) log(…argsopt)
- Description:
Print all arguments into the console, for debugging purposes, if the first arg is an error only print the error
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
args |
any |
<optional> <repeatable> |
print all arguments |
(static) murmurHash3(key) → {number}
- Description:
32-bit MurmurHash3 implemented by bryc (github.com/bryc)
Parameters:
| Name | Type | Description |
|---|---|---|
key |
string | input string |
Returns:
| Type | Description |
|---|---|
| number |
hash number |
(static) newError(message, statusopt, codeopt)
- Description:
Return a new Error object, message can be a string or an object with message, code, status properties. The default error status is 400 if not specified.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
message |
string | object | ||
status |
number |
<optional> |
|
code |
string |
<optional> |
(static) notifyWorkers(filter)
- Description:
Send a message to all workers
Parameters:
| Name | Type | Description |
|---|---|---|
filter |
string | number | object |
(static) now()
- Description:
Return number of seconds for current time
(static) objClone(obj, …argsopt) → {object}
- Description:
A shallow copy of an object, it is deeper than Object.assign for arrays, objects, sets and maps, these created new but all other types are just references as in Object.assign
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
obj |
object | first argument is the object to clone, can be null |
|
args |
any |
<optional> <repeatable> |
additional arguments are treated as object to be merged into the result using Object.assign |
Returns:
| Type | Description |
|---|---|
| object |
Example
const a = { 1: 2, a: [1, 2] }
const b = lib.objClone(a, { "3": 3, "4": 4 })
b.a.push(3)
a.a.length != b.length
(static) 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
Parameters:
| Name | Type | Attributes | Description | ||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
object |
<optional> |
Properties
|
Returns:
| Type | Description |
|---|---|
| int |
the size of the whole object |
(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
Parameters:
| Name | Type | Description |
|---|---|---|
header |
string | Cookie header |
Returns:
| Type | Description |
|---|---|
| object |
(static) parseTime()
- 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
(static) runCallback()
- Description:
Run delayed callback for the message previously registered with the
deferCallbackmethod. The message must have__deferIdproperty which is used to find the corresponding callback, if the msg is a JSON string it will be converted into the object.Same parent object must be used for
deferCallbackand this method.
(static) shuffle(list) → {Array.<any>}
- Description:
Randomize a list items in place
Parameters:
| Name | Type | Description |
|---|---|---|
list |
Array.<any> |
Returns:
| Type | Description |
|---|---|
| Array.<any> |
(static) sleep(delay) → {Promise}
- Description:
Async sleep version
Parameters:
| Name | Type | Description |
|---|---|---|
delay |
int | number of milliseconds to wait |
Returns:
| Type | Description |
|---|---|
| Promise |
(static) slug(optionsopt) → {string}
- Description:
Generate a 22 chars slug from an UUID
Parameters:
| Name | Type | Attributes | Description | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
object |
<optional> |
Properties
|
Returns:
| Type | Description |
|---|---|
| string |
(static) sortByVersion()
- Description:
Sort a list be version in descending order, an item can be a string or an object with a property to sort by, in such case
namemust be specified which property to use for sorting. The name format is assumed to be:XXXXX-N.N.N
(static) strftimeMap()
- Description:
Format date object according to Unix stftime function
(static) stringify()
- Description:
JSON stringify without exceptions, on error just returns an empty string and logs the error
(static) suuid(prefixopt, optionsopt) → {string}
- Description:
Short unique id within a microsecond
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
prefix |
string |
<optional> |
prepend with prefix |
options |
object |
<optional> |
same options as for module:lib.getHashid |
Returns:
| Type | Description |
|---|---|
| string |
generated hash |
(static) textToEntity()
- Description:
Convert all special symbols into html entities
(static) textToXml()
- Description:
Convert all special symbols into xml entities
(static) toAge()
- Description:
Given time in msecs, return how long ago it happened
- short - if true use first letters only
- round - a number, 1 return only 1st part, 2 - 1st and 2nd parts
(static) toBase32(bug, optionsopt) → {string}
- Description:
Convert a Buffer into base32 string
Parameters:
| Name | Type | Attributes | Description | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bug |
Buffer | inout buffer |
|||||||||||||
options |
object |
<optional> |
Properties
|
Returns:
| Type | Description |
|---|---|
| string |
encoded value |
(static) toBase62()
- Description:
Return base62 representation for a number
(static) toBase64url()
- Description:
Encode a string into Base64 url safe version
(static) toBool(val, dfltopt) → {boolean}
- Description:
Return true if value represents true condition, i.e. non empty value
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
val |
string | number | boolean | ||
dflt |
any |
<optional> |
Returns:
| Type | Description |
|---|---|
| boolean |
(static) toCamel(name, charsopt) → {string}
- Description:
Convert into camelized form
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
name |
string | ||
chars |
string |
<optional> |
can define the separators, default is [ _.:-] |
Returns:
| Type | Description |
|---|---|
| string |
(static) toClamp(num, min, max) → {number}
- Description:
Return a number clamped between the range
Parameters:
| Name | Type | Description |
|---|---|---|
num |
number | |
min |
number | |
max |
number |
Returns:
| Type | Description |
|---|---|
| number |
(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.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
val |
string | Date | number | ||
dflt |
any |
<optional> |
|
invalid |
boolean |
<optional> |
Returns:
| Type | Description |
|---|---|
| Date |
(static) toDigits(str) → {string}
- Description:
Strip all non-digit characters from a string
Parameters:
| Name | Type | Description |
|---|---|---|
str |
string | input string |
Returns:
| Type | Description |
|---|---|
| string |
only digit in the result |
(static) toDuration()
- Description:
Return duration in human format, mtime is msecs
- short - if true use first letters only
- round - a number, 1 return only 1st part, 2 - 1st and 2nd parts
(static) toEmail()
- Description:
Return an email address if valid,
options.parsemakes it extract the email fromname <email>format
(static) toFlags()
- Description:
Flags command utility, the commands are:
- add - adds the
nameflags to the list if does not exists, returns the same array - update - adds new flags and removes flags that starts with - , returns the same array
- concat - same as add but always returns a new list
- del - removes the flags
name, returns the same array - present - returns only flags that present in the list
name - absent - returns only flags that are not present in the list
name
- add - adds the
(static) toFormat()
- Description:
Convert a list of records into the specified format, supported formats are:
xml, csv, json, jsontext.- For
csvthe default separator is comma but can be specified withoptions.separator. To produce columns header specifyoptions.header. - For
jsonformat puts each record as a separate JSON object on each line, so to read it back it will require to read every line and parse it and add to the list. - For
xmlformat the name of the row tag is<row>but can be specified withoptions.tag.
All formats support the property
options.allowwhich is a list of property names that are allowed only in the output for each record, non-existent properties will be replaced by empty strings.The
mappingobject property can redefine different tag/header names to be put into the file instead of the exact column names from the records.- For
(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
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
val |
string | number | Date | ||
dflt |
any |
<optional> |
Returns:
| Type | Description |
|---|---|
| number |
(static) toNumber(val, optionsopt) → {number}
- Description:
Safe convertion to a number, no expections, uses 0 instead of NaN, handle booleans, if float specified, returns as float.
Parameters:
| Name | Type | Attributes | Description | ||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
val |
any | to be converted to a number |
|||||||||||||||||||||||||||||||||||||||||||||
options |
object |
<optional> |
Properties
|
Returns:
| Type | Description |
|---|---|
| number |
Example
lib.toNumber("123")
lib.toNumber("1.23", { float: 1, dflt: 0, min: 0, max: 2 })
(static) toParams(query, schema, optionsopt) → {string|object}
- Description:
Process incoming query and convert parameters according to the type definition, the schema contains the definition of the paramaters against which to validate incoming data. It is an object with property names and definitoons that at least must specify the type, all other options are type specific.
Returns a string message on error or an object
Parameters:
| Name | Type | Attributes | Description | ||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
query |
object | request query object, usually req.query or req.body |
|||||||||||||||||||||||||||||
schema |
object | an object in format: { name: module:lib.ParamsOptions, ...} |
|||||||||||||||||||||||||||||
options |
object |
<optional> |
options can define the following properties to customize convertion: Properties
|
Returns:
| Type | Description |
|---|---|
| string | object |
string in case of an error or an object |
Example
var query = lib.toParams(req.query, {
id: { type: "int" },
count: { type: "int", min: 1, max: 10, dflt: 5 },
age: { type: "int", minnum: 10, maxnum: 99 },
name: { type: "string", max: 32, trunc: 1 },
pair: { type: "map", maptype: "int" },
code: { type: "string", regexp: /^[a-z]-[0-9]+$/, errmsg: "Valid code is required" },
start: { type: "token", required: 1 },
email: { type: "list", datatype: "email", novalue: ["a@a"] },
email1: { type: "email", required: { email: null } },
data: { type: "json", datatype: "obj" },
mtime: { type: "mtime", name: "timestamp" },
date: { type: "date", mindate: new Date(2000,1,1) },
flag: { type: "bool", novalue: false },
descr: { novalue: { name: "name", value: "test" }, replace: { "<": "!" } },
internal: { ignore: 1 },
tm: { type: "timestamp", optional: 1 },
ready: { value: "ready" },
state: { values: [ "ok","bad","good" ] },
status: { value: [ "ok","done" ] },
obj: { type: "obj", params: { id: { type: "int" }, name: {} } },
arr: { type: "array", params: { id: { type: "int" }, name: {} } },
ssn: { type: "string", regexp: /^[0-9]{3}-[0-9]{3}-[0-9]{4}$/, errmsg: "Valid SSN is required" },
phone: { type: "list", datatype: "number" },
}, {
defaults: {
start: { secret: req.user.secret },
name: { dflt: "test" },
count: { max: 100 },
email: { ignore: req.user.roles != "admin" },
"*.string": { max: 255 },
'*': { maxlist: 255 },
});
if (typeof query == "string) return api.sendReply(res, 400, query);
(static) toPrice()
- Description:
Return a test representation of a number according to the money formatting rules, default is en-US, options may include: currency(USD), display(symbol), sign(standard), min(2), max(3)
(static) toRFC3339()
- Description:
Return RFC3339 formatted timestamp for a date or current time
(static) toRegexp()
- 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:
- ingoreCase - similar to i
- globalMatch - similar to m
- multiLine - similar to m
- unicode - similar to u
- sticky - similar to y
- escape - escape all special symbols or symbol
e
(static) toRegexpMap()
- Description:
Add a regexp to the list of regexp objects, this is used in the config type
regexpmap.
(static) toRegexpObj()
- Description:
Add a regexp to the object that consist of list of patterns and compiled regexp, this is used in the config type
regexpobj
(static) toSize()
- Description:
Return size human readable format
(static) toString(val) → {string}
- Description:
Convert a value to a string, use default Javascript toString convertion of any object
Parameters:
| Name | Type | Description |
|---|---|---|
val |
any |
Returns:
| Type | Description |
|---|---|
| string |
(static) toTemplate()
- Description:
Given a template with @..@ placeholders, replace each placeholder with the value from the obj. The
objcan be an object or an array of objects in which case all objects will be checked for the value until non empty.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@
Encoding options:
- url, base64, entity, strftime, mtime
- d-url, d-base64, d-entity - decode value instead of encode it
The options if given may provide the following:
- allow - placeholders with a name present in this list will be replaced, all other will be replaced with empty string
- skip - placeholders with a name present in this list will be ignored, the placeholer will be kept
- only - placeholders with a name present in this list will be replaced only, all other will be ignored and kept as placeholders
- encoding - can be url or base64, the replaced values will be encoded accordingly
- separator1 - left side of the placehoder, default is @
- separator2 - right side of the placeholder, default is @
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:
Example
lib.toTemplate("http://www.site.com/@code@/@id@", { id: 123, code: "YYY" }, { encoding: "url" })
lib.toTemplate("Hello @name|friend@!", {})
(static) toTitle(name, minlenopt) → {string}
- Description:
Convert text into capitalized words, if it is less or equal than minlen leave it as is
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
name |
string | ||
minlen |
int |
<optional> |
Returns:
| Type | Description |
|---|---|
| string |
(static) toUncamel(str, sepopt) → {string}
- Description:
Convert Camel names into names separated by the given separator or dash(-) if not.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
str |
string | ||
sep |
string |
<optional> |
Returns:
| Type | Description |
|---|---|
| string |
(static) toUrl()
- Description:
Return a well formatted and validated url or empty string
(static) toValue()
- 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, special case if the type is "" or null return the value as is without any conversion
(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.
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) traceError(err)
- Description:
Returns the error stack or the error itself, to be used in error messages
Parameters:
| Name | Type | Description |
|---|---|---|
err |
Error |
(static) tryCall(callback, …argsopt) → {any}
- Description:
Run a callback if a valid function, all arguments after the callback will be passed as is, report a warning if callback is not a function but not empty
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
callback |
function | try to call this function |
|
args |
any |
<optional> <repeatable> |
pass the rest arguments to the function |
Returns:
| Type | Description |
|---|---|
| any |
the function result |
(static) tryCatch(callback, …argsopt)
- Description:
Run a callback inside try..catch block, all arguments after the callback will be passed as is, in case of error all arguments will be printed in the log. If no callback passed do nothing.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
callback |
function | try to call this function |
|
args |
any |
<optional> <repeatable> |
pass the rest arguments to the function |
(static) tryLater(callback, timeout, …argsopt)
- Description:
Run a callback after timeout, returns a function so it can be used instead of actual callback, report a warning if callback is not a function but not empty
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) tzName()
- Description:
Return a timezone human name if matched (EST, PDT...), tz must be in GMT-NNNN format
(static) unescape()
- Description:
Convert escaped characters into native symbols
(static) unicode2Ascii()
- 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
(static) uuid(prefixopt) → {string}
- Description:
Unique Id (UUID v4) without any special characters and in lower case
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
prefix |
string |
<optional> |
prepend with prefix |
Returns:
| Type | Description |
|---|---|
| string |
(static) weekDate()
- Description:
Return first day of the week by ISO week number
(static) weekOfYear()
- Description:
Return an ISO week number for given date, from https://www.epochconverter.com/weeknumbers
(static) xmlParse()
- Description:
Same arguments as for module:lib.jsonParse
(inner) onDeferCallback()
- Description:
To be called on timeout or when explicitely called by the
runCallback, it is called in the context of the message.