Reference

February 23, 2021 ยท View on GitHub

Index

The generated reference for Jsi builtin commands.

Array

Provide access to array objects.

MethodFunction Argument TypesDescription
Array(...):arrayjsi_Array constructor.
concat(...):arrayReturn array with args appended.
every(callback:function)Returns true if every value in array satisfies the test.
fill(value:any, start:number=0, end:number=-1):arrayFill an array with values.
filter(callback:function, thisArg:object=void):arrayReturn a filtered array.
find(callback:function)Returns the value of the first element in the array that satisfies the test.
findIndex(callback:function)Returns the index of the first element in the array that satisfies the test.
flat(depth:number=1):arrayFlatten an arra.
forEach(callback:function, thisArg:object=void):voidInvoke function with each item in object.
includes(val:any)Returns true if array contains value.
indexOf(str:any, startIdx:number=0):numberReturn index of first occurrance in array.
isArray():booleanTrue if val array.
join(sep:string=''):stringReturn elements joined by char.
lastIndexOf(val:any, start:number=0):numberReturn index of last occurence in array.
map(callback:function, thisArg:object=void):arrayCreates a new array with the results of calling a provided function on every element in this array.
pop()Remove and return last element of array.
push(val:any, ...):numberPush one or more elements onto array and return size.
reduce(callback:function, initial:any)Return a reduced array.
reduceRight(callback:function, initial:any)Return a reduced array.
reverse():arrayReverse order of all elements in an array.
shift()Remove first element and shift downwards.
sizeOf():numberReturn size of array.
slice(start:number, end:number=void):arrayReturn sub-array.
some(callback:function, thisArg:object=void):booleanReturn true if function returns true some element.
sort(options:function|object=void):arraySort an array.
splice(start:number, howmany:number=void, ...):arrayChange the content of an array, adding new elements while removing old elements.
unshift(...):numberAdd new elements to start of array and return size.

Array sort

OptionTypeDescriptionFlags
modeSTRKEYMode to sort by. (one of: default, desc, dict, nocase)
compareFUNCFunction to do comparison. @function(val1,val2)
uniqueBOOLEliminate duplicate items.

Boolean

A Boolean object.

MethodFunction Argument TypesDescription
Boolean(bool:boolean=false):booleanBoolean constructor.

Channel

Commands for accessing Channel objects for file IO.

MethodFunction Argument TypesDescription
Channel(file:string, mode:string='r'):userobjA file input/output object. The mode string is r or w and an optional +.
close():booleanClose the file.
eof():booleanReturn true if read to end-of-file.
filename():stringGet file name.
flush():numberFlush file output.
gets():string|voidGet one line of input.
lstat():objectReturn status for file.
mode():stringGet file mode used with open.
open(file:string, mode:string='r'):booleanOpen the file (after close).
puts(str):booleanWrite one line of output.
read(size:number=-1):string|voidRead some or all of file.
seek(pos:number, whence:string):numberSeek to position. Return 0 if ok.
stat():objectReturn status for file.
tell():numberReturn current position.
truncate(pos:number):numberTruncate file.
write(data):numberWrite data to file.

Event

Event management.

MethodFunction Argument TypesDescription
clearInterval(id:number):voidDelete an event (created with setInterval/setTimeout).
info(id:number):objectReturn info for the given event id.
names():arrayReturn list event ids (created with setTimeout/setInterval).
setInterval(callback:function, millisecs:number):numberSetup recurring function to run every given millisecs.
setTimeout(callback:function, millisecs:number):numberSetup function to run after given millisecs.
update(options:number|object=void):numberService all events, eg. setInterval/setTimeout. Returns the number of events processed. Events are processed until minTime (in milliseconds) is exceeded, or forever if -1. The default minTime is 0, meaning return as soon as no events can be processed. A positive mintime will result in sleeps between event checks.

Event update

OptionTypeDescriptionFlags
maxEventsINTMaximum number of events to process (or -1 for all).
maxPassesINTMaximum passes through event queue.
minTimeINTMinimum milliseconds before returning, or -1 to loop forever (default is 0).
sleepINTTime to sleep time (in milliseconds) between event checks. Default is 1.

File

Commands for accessing the filesystem.

MethodFunction Argument TypesDescription
atime(file:string):numberReturn file Jsi_Access time.
chdir(file:string)Change current directory.
chmod(file:string, mode:number)Set file permissions.
copy(src:string, dest:string, force:boolean=false)Copy a file to destination. Directories are not handled. The third argument if given is a boolean force value which if true allows overwrite of an existing file.
dirname(file:string):stringReturn directory path.
executable(file:string):booleanReturn true if file is executable.
exists(file:string):booleanReturn true if file exists.
extension(file:string):stringReturn file extension.
glob(options:regexp|string|object|null='*', opts:function|object|null=void):arrayReturn list of files in dir with optional pattern match. With no arguments (or null) returns all files/directories in current directory. The first argument can be options, a pattern (either a glob or regexp) of the files to return. When the second argument is a function, it is called with each path, and filter on false. Otherwise second argument must be a set of options.
isdir(file:string):booleanReturn true if file is a directory.
isfile(file:string):booleanReturn true if file is a normal file.
isrelative(file:string):booleanReturn true if file path is relative.
join(path1:string, path2:string):stringJoin two file realpaths, or just second if an absolute path.
link(src:string, dest:string, ishard:boolean=false)Link a file. The second argument is the destination file to be created. If a third bool argument is true, a hard link is created.
lstat(file:string):objectReturn status info for file.
mkdir(file:string,force:boolean=false)Create a directory: force creates subdirs.
mknod(file:string, mode:number, dev:number)Create unix device file using mknod.
mtime(file:string):numberReturn file modified time.
normalize(file:string):stringReturn normalized file path.
owned(file:string):booleanReturn true if file is owned by user.
perms(file:string):stringReturn perms string.
pwd():stringReturn current directory.
read(file:string, mode:string='rb'):stringRead a file.
readable(file:string):booleanReturn true if file is readable.
readlink(file:string):stringRead file link destination.
realpath(file:string):stringReturn absolute file name minus .., ./ etc.
remove(file:string, force:boolean=false)Delete a file or direcotry.
rename(src:string, dest:string, force:boolean=false)Rename a file, with possible overwrite.
rootname(file:string):stringReturn file name minus extension.
size(file:string):numberReturn size for file.
stat(file:string):objectReturn status info for file.
tail(file:string):stringReturn file name minus dirname.
tempfile(file:string)Create a temp file.
truncate(file:string, size:number)Truncate file.
writable(file:string):booleanReturn true if file is writable.
write(file:string, str:string, mode:string='wb+'):numberWrite a file.

File glob

OptionTypeDescriptionFlags
dirSTRINGThe start directory: set in "prefix" to have this prepended to result.
maxDepthINTMaximum directory depth to recurse into.
maxDiscardINTMaximum number of items to discard before giving up.
dirFilterFUNCFilter function for directories, returning false to discard. @function(dir:string)
filterFUNCFilter function to call with each file, returning false to discard. @function(file:string)
limitINTThe maximum number of results to return/count: -1 is unlimited (Interp.maxArrayList).
noTypesSTRKEYFilter files to exclude these "types".
patternVALUEPattern to use if arg 1 is null.
prefixSTRKEYString prefix to prepend to each file in result list.
recurseBOOLRecurse into sub-directories.
retCountBOOLReturn only the count of matches.
retInfoBOOLReturn file info: size, uid, gid, mode, name, and path.
tailsBOOLReturned only tail of path.
typesSTRKEYFilter files to include type: one or more of chars 'fdlpsbc' for file, directory, link, etc.

Function

Commands for accessing functions.

MethodFunction Argument TypesDescription
Function():functionFunction constructor (unimplemented).
apply(thisArg:null|object|function, args:array=void)Call function passing args array.
bind(thisArg:object|function=null,...)Return function that calls bound function prepended with thisArg+arguments.
call(thisArg:null|object|function, arg1, ...)Call function with args.

Info

Commands for inspecting internal state information in JSI.

MethodFunction Argument TypesDescription
argv0():string|voidReturn initial start script file name.
cmds(val:string|regexp='*', options:object=void):array|objectReturn details or list of matching commands.
completions(str:string, start:number=0, end:number=void):arrayReturn command completions on portion of string from start to end.
data(val:string|regexp|object=void):array|objectReturn list of matching data (non-functions). Like info.vars(), but does not return function values.
error():objectReturn file and line number of error (used inside catch).
event(id:number=void):array|objectList events or info for 1 event (setTimeout/setInterval). With no args, returns list of all outstanding events. With one arg, returns infofor the given event id.
execZip():string|voidIf executing a .zip file, return file name.
executable():stringReturn name of executable.
files():arrayReturn list of all sourced files.
funcs(arg:string|regexp|function|object=void):array|objectReturn details or list of matching functions.
interp(interp:userobj=void):objectReturn info on given or current interp.
isMain():booleanReturn true if current script was the main script invoked from command-line.
keywords(isSql=false, name:string=void):boolean|arrayReturn/lookup reserved keyword.
level(level:number=void):number|array|objectReturn current level or details of a call-stack frame. With no arg, returns the number of the current stack frame level. Otherwise returns details on the specified level. The topmost level is 1, and 0 is the current level, and a negative level translates as relative to the current level.
locals(filter:boolean=void):objectReturn locals; if filter=true/false omit vars/functions.
lookup(name:string)Given string name, lookup and return value, eg: function.
methods(val:string|regexp):array|objectReturn functions and commands.
named(name:string=void):array|userobjReturns command names for builtin Objects, eg: 'File', 'Interp', sub-Object names, or the named object.
obj(val:object):objectReturn details about object.
options(ctype:boolean=false):arrayReturn Option type name, or with true the C type.
package(pkgName:string):object|nullReturn info about provided package if exists, else null.
platform():objectN/A. Returns general platform information for JSI.
script(func:function|regexp=void):string|array|voidGet current script file name, or file containing function.
scriptDir():string|voidGet directory of current script.
vars(val:string|regexp|object=void):array|objectReturn details or list of matching variables. Returns all values, data or function.
version(full:boolean|number|string=false, ver:number|string=void):number|objectReturn version: when full=true returns as object.

Info cmds

OptionTypeDescriptionFlags
fullBOOLReturn full path.
constructorBOOLDo not exclude constructor.

Interp

Commands for accessing interps.

MethodFunction Argument TypesDescription
Interp(options:object=void):userobjCreate a new interp.
alias(name:string=void, func:function|null=void, args:array|null=void, async=false)Set/get global alias bindings for command in an interp. With 0 args, returns list of all aliases in interp. With 1 arg returns func for given alias name. With 2 args where arg2 == null, returns args for given alias name . With 3 args, create/update an alias for func and args. Delete an alias by creating it with null for both func and args.
call(funcName:string, args:array, wait:boolean=false)Call named function in subinterp. Invoke function in sub-interp with arguments. Since interps are not allowed to share objects, data is automatically cleansed by encoding/decoding to/from JSON if required. Unless an 'async' parameter is true call is acyncronous. Otherwise waits until the sub-interp is idle, to make call and return result.
conf(options:string|object=void)Configure option(s).
eval(js:string, async:boolean=false)Interpret script within sub-interp. When the 'async' option is used on a threaded interp, the script is queued as an Event.
info():objectReturns internal statistics about interp.
source(file:string, async:boolean=false)Interpret file within sub-interp. When the 'async' option is used on a threaded interp, the script is queued as an Event.
uplevel(js:string, level:number=0)Interpret code at the given stack level. The level argument is as returned by Info.level(). Not supported with threads.
value(varName:string, level:number=0)Lookup value of variable at stack level.

Interp new

OptionTypeDescriptionFlags
argsARRAYThe console.arguments for interp.initOnly
assertsBOOLShortcut for toggling log:assert and assertMode=throw.
assertModeSTRKEYAction upon assert failure. (one of: log, puts, throw)
autoFilesARRAYFile(s) to source for loading Jsi_Auto to handle unknown commands.
busyCallbackCUSTOMCommand in parent interp (or noOp) to periodically call.
busyIntervalINTCall busyCallback command after this many op-code evals (100000).
confFileSTRKEYConfig file of options in JSON non-strict format.initOnly
coverageBOOLOn exit generate detailed code coverage for function calls (with profile).
debugOptsOptionsOptions for debugging.
interactiveBOOLForce interactive mode. ie. ignore no_interactive flag.initOnly
hasOpenSSLBOOLWebSocket compiled with SSL is available.initOnly
historyFileSTRKEYFor readline, file to use for history (~/.jsish_history).
isSafeBOOLIs this a safe interp (ie. with limited or no file access).initOnly
jsppCharsSTRKEYLine preprocessor when sourcing files. Line starts with first char, and either ends with it, or matches string.
jsppCallbackFUNCCommand to preprocess lines that match jsppChars. Call func(interpName:string, opCnt:number).
lockTimeoutINTThread time-out for mutex lock acquires (milliseconds).
lockDownSTRKEYDirectory to Safe-lockdown interpreter to.
logOptsOptionsOptions for log output to add file/line/time.
logARRAYLogging flags. (zero or more of: bug, assert, debug, trace, test, info, warn, error, parse)noCase
maxDepthINTDepth limit of recursive function calls (1000).
maxDumpStackUINTMaximum stack dump length (100).
maxDumpArgsUINTMaximum arg length in stack dump (80).
maxArrayListUINTMaximum array convertable to list (100000).
maxIncDepthINTMaximum allowed source/require nesting depth (50).
maxInterpDepthINTMaximum nested subinterp create depth (10).
maxUserObjsINTMaximum number of 'new' object calls, eg. File, RegExp, etc.
maxOpCntINTExecution limit for op-code evaluation.initOnly
memDebugINTMemory debugging level: 1=summary, 2=detail.
memLeakCntINTLeak memory count due to object added to self.initOnly
nameSTRKEYOptional text name for this interp.
noAutoLoadBOOLDisable autoload.
noCheckBOOLDisable type checking.
noConfigBOOLDisable use of Interp.conf to change options after create.initOnly
noErrorBOOLType checks failures are warning.
noES6BOOLWarn/error when ES6 features are used, eg. arrow funcs or let/const.
noEvalBOOLDisable eval: just parses file to check syntax.initOnly
noInputBOOLDisable use of console.input().
noLoadBOOLDisable load of shared libs.
noNetworkBOOLDisable new Socket/WebSocket, or load of builtin MySql.
noStderrBOOLMake puts, log, assert, etc use stdout.
noSubInterpsBOOLDisallow sub-interp creation.
onCompleteFUNCFunction to return commands completions for interactive mode. Default uses Info.completions . @function(prefix:string, start:number, end:number)
onEvalFUNCFunction to get control for interactive evals. @function(cmd:string)
onExitFUNCCommand to call in parent on exit, returns true to continue. @function()initOnly
pkgDirsARRAYlist of library directories for require() to search.
profileBOOLOn exit generate profile of function calls.
retValueVALUEReturn value from last eval.readOnly
safeModeSTRKEYIn safe mode source() support for pwd and script-dir . (one of: none, read, write, writeRead, lockdown)initOnly
safeReadDirsARRAYIn safe mode, files/dirs to allow reads to.initOnly
safeWriteDirsARRAYIn safe mode, files/dirs to allow writes to.initOnly
safeExecPatternSTRKEYIn safe mode, regexp pattern allow exec of commands.initOnly
scriptStrSTRKEYInterp init script string.initOnly
scriptFileSTRINGInterp init script file.
stdinStrSTRINGString to use as stdin for console.input().
stdoutStrSTRINGString to collect stdout for puts().
subOptsOptionsInfrequently used sub-options.
subthreadBOOLCreate a threaded Interp.initOnly
traceCallARRAYTrace commands. (zero or more of: funcs, cmds, new, return, args, notrunc, noparent, full, before)
traceOpINTSet debugging level for OPCODE execution.
tracePutsBOOLTrace puts by making it use logOpts.
typeCheckARRAYType-check control options. (zero or more of: noreturn, noundef, nowith, builtins, funcdecl)
typeWarnMaxINTType checking is silently disabled after this many warnings (50).
udataOBJUser data.
testModeUINTUnit test control bits: 1=subst, 2=Puts with file:line prefix.

Interp debugOpts

OptionTypeDescriptionFlags
debugCallbackCUSTOMCommand in parent interp for handling debugging.
doContinueBOOLContinue execution until breakpoint.
forceBreakBOOLForce debugger to break.
includeOnceBOOLSource the file only if not already sourced.
includeTraceBOOLTrace includes.
minLevelINTDisable eval callback for level higher than this.
msgCallbackCUSTOMComand in parent interp to handle Jsi_LogError/Jsi_LogWarn,...
pkgTraceBOOLTrace package loads.
putsCallbackCUSTOMComand in parent interp to handle puts output.
traceCallbackCUSTOMComand in parent interp to handle traceCall.
testFmtCallbackCUSTOMComand in parent interp to format testing strings.

Interp logOpts

OptionTypeDescriptionFlags
timeBOOLPrefix with time.
dateBOOLPrefix with date.
fileBOOLOuptut contains file:line.
funcBOOLOutput function.
fullBOOLShow full file path.
ftailBOOLShow tail of file only, even in LogWarn, etc.
beforeBOOLOutput file:line before message string.
isUTCBOOLTime is to be UTC.
timeFmtSTRKEYA format string to use with strftime.
captureBOOLCapture first error.
chanUSEROBJChannel to send output to.

Interp subOpts

OptionTypeDescriptionFlags
blacklistSTRKEYComma separated modules to disable loading for.initOnly
compatBOOLIgnore unknown options via JSI_OPTS_IGNORE_EXTRA in option parser.
dblPrecINTFormat precision of double where 0=max, -1=max-1, ... (max-1).
isttyBOOLIndicates interp is in interactive mode.readOnly
nofreezeBOOLmoduleOpts freeze disabled by default.
logColNumsBOOLDisplay column numbers in error messages.
logAllowDupsBOOLLog should not filter out duplicate messages.
mutexUnlockBOOLUnlock own mutex when evaling in other interps (true).initOnly
noprotoBOOLDisable support of the OOP symbols: proto, prototype, constructor, etc.
noFuncStringBOOLDisable viewing code body for functions.initOnly
noRegexBOOLDisable viewing code for functions.initOnly
noReadlineBOOLIn interactive mode disable use of readline.
outUndefBOOLIn interactive mode output result values that are undefined.
promptSTRKEYPrompt for interactive mode ('$ ').
prompt2STRKEYPrompt for interactive mode line continue ('> ').
traceAccessBOOLTrace set/gets setup using Jsi_ObjAccessorWithSpec.

JSON

Commands for handling JSON data.

MethodFunction Argument TypesDescription
check(str:string, strict:boolean=true):booleanReturn true if str is JSON.
parse(str:string, strict:boolean=true)Parse JSON and return js.
stringify(value:any, strict:null|boolean=true, indent:number=2):stringReturn JSON from a js object.

Math

Commands performing math operations on numbers.

MethodFunction Argument TypesDescription
abs(num:number):numberReturns the absolute value of x.
acos(num:number):numberReturns the arccosine of x, in radians.
asin(num:number):numberReturns the arcsine of x, in radians.
atan(num:number):numberReturns the arctangent of x as a numeric value between -PI/2 and PI/2 radians.
atan2(x:number, y:number):numberReturns the arctangent of the quotient of its arguments.
ceil(num:number):numberReturns x, rounded upwards to the nearest integer.
cos(num:number):numberReturns the cosine of x (x is in radians).
exp(num:number):numberReturns the value of Ex.
floor(num:number):numberReturns x, rounded downwards to the nearest integer.
log(num:number):numberReturns the natural logarithm (base E) of x.
max(x:number, y:number, ...):numberReturns the number with the highest value.
min(x:number, y:number, ...):numberReturns the number with the lowest value.
pow(x:number, y:number):numberReturns the value of x to the power of y.
random():numberReturns a random number between 0 and 1.
round(num:number):numberRounds x to the nearest integer.
sin(num:number):numberReturns the sine of x (x is in radians).
sqrt(num:number):numberReturns the square root of x.
srand(seed:number):numberSet random seed.
tan(num:number):numberReturns the tangent of an angle.

MySql

Commands for accessing mysql databases.

MethodFunction Argument TypesDescription
MySql(options:object=void):userobjCreate a new db connection to a MySql database:.
affectedRows():numberReturn affected rows.
complete(sql:string):booleanReturn true if sql is complete.
conf(options:string|object=void)Configure options.
errorNo():numberReturn error code returned by most recent call to mysql3_exec().
errorState():stringReturn the mysql error state str.
eval(sql:string):numberRun sql commands without input/output.
exists(sql:string):booleanExecute sql, and return true if there is at least one result value.
info():objectReturn info about last query.
lastQuery():stringReturn info string about most recently executed statement.
lastRowid():numberReturn rowid of last insert.
onecolumn(sql:string)Execute sql, and return a single value.
ping(noError:boolean=false):numberPing connection.
query(sql:string, options:function|string|array|object=void)Run sql query with input and/or outputs..
reconnect():voidReconnect with current settings.
reset():numberReset connection.

MySql new

OptionTypeDescriptionFlags
bindWarnBOOLTreat failed variable binds as a warning.initOnly
databaseSTRKEYDatabase to use.initOnly
debugARRAYEnable debug trace for various operations. (zero or more of: eval, delete, prepare, step)
enableMultiBOOLAccept muiltiple semi-colon separated statements in eval().initOnly
errorCntINTCount of errors.readOnly
queryOptsOptionsDefault options for exec.
forceIntBOOLBind float as int if possible.
hostSTRINGIP address or host name for mysqld (default is 127.0.0.1).
maxStmtsINTMax cache size for compiled statements.
nameDSTRINGName for this db handle.
numStmtsINTCurrent size of compiled statement cache.readOnly
passwordSTRKEYDatabase password..initOnly
portINTIP port for mysqld.initOnly
reconnectBOOLReconnect.
sslKeySTRINGSSL key.
sslCertSTRINGSSL Cert.
sslCASTRINGSSL CA.
sslCAPathSTRINGSSL CA path.
sslCipherSTRINGSSL Cipher.
udataOBJUser data..
userSTRKEYDatabase user name. Default is current user-name..initOnly
versionDOUBLEMysql version number.readOnly

MySql queryOpts

OptionTypeDescriptionFlags
callbackFUNCFunction to call with each row result. @function(values:object)
headersBOOLFirst row returned contains column labels.
limitINTMaximum number of returned values.
mapundefBOOLIn variable binds, map an 'undefined' var to null.
maxStringINTIf not using prefetch, the maximum string value size (0=8K).
modeSTRKEYSet output mode of returned data. (one of: rows, arrays, array1d, list, column, json, json2, html, csv, insert, line, tabs, none)
nocacheBOOLDisable query cache.
noNamedParamsBOOLDisable translating sql to support named params.
nullvalueSTRKEYNull string output (for non-json mode).
objOptionsOptions for object.
paramVarARRAYArray var to use for parameters.
prefetchBOOLLet client library cache entire results.
separatorSTRKEYSeparator string (for csv and text mode).
tableSTRKEYTable name for mode=insert.
typeCheckSTRKEYType check mode (error). (one of: convert, error, warn, disable)
valuesARRAYValues for ? bind parameters.
widthCUSTOMIn column mode, set column widths.

MySql obj

OptionTypeDescriptionFlags
nameSTRKEYName of object var data source for %s.
skipARRAYObject members to ignore.
getSqlBOOLReturn expanded SQL without evaluating.
defaultNullBOOLCreate with DEFAULT NULL.
noChecksBOOLCreate with no CHECK constraints.
noDefaultsBOOLCreate with no defaults.
noTypesBOOLCreate with no types.

MySql query

OptionTypeDescriptionFlags
callbackFUNCFunction to call with each row result. @function(values:object)
headersBOOLFirst row returned contains column labels.
limitINTMaximum number of returned values.
mapundefBOOLIn variable binds, map an 'undefined' var to null.
maxStringINTIf not using prefetch, the maximum string value size (0=8K).
modeSTRKEYSet output mode of returned data. (one of: rows, arrays, array1d, list, column, json, json2, html, csv, insert, line, tabs, none)
nocacheBOOLDisable query cache.
noNamedParamsBOOLDisable translating sql to support named params.
nullvalueSTRKEYNull string output (for non-json mode).
obj[Options](#MySql query-obj)Options for object.
paramVarARRAYArray var to use for parameters.
prefetchBOOLLet client library cache entire results.
separatorSTRKEYSeparator string (for csv and text mode).
tableSTRKEYTable name for mode=insert.
typeCheckSTRKEYType check mode (error). (one of: convert, error, warn, disable)
valuesARRAYValues for ? bind parameters.
widthCUSTOMIn column mode, set column widths.

MySql query obj

OptionTypeDescriptionFlags
nameSTRKEYName of object var data source for %s.
skipARRAYObject members to ignore.
getSqlBOOLReturn expanded SQL without evaluating.
defaultNullBOOLCreate with DEFAULT NULL.
noChecksBOOLCreate with no CHECK constraints.
noDefaultsBOOLCreate with no defaults.
noTypesBOOLCreate with no types.

Number

Commands for accessing number objects.

MethodFunction Argument TypesDescription
Number(num:string=0):numberNumber constructor.
isFinite():booleanReturn true if is finite.
isInteger():booleanReturn true if is an integer.
isNaN():booleanReturn true if is NaN.
isSafeInteger():booleanReturn true if is a safe integer.
toExponential(num:number):stringConverts a number into an exponential notation.
toFixed(num:number=0):stringFormats a number with x numbers of digits after the decimal point.
toPrecision(num:number):stringFormats a number to x length.
toString(radix:number=10):stringConvert to string.

Object

Commands for accessing Objects.

MethodFunction Argument TypesDescription
Object(val:object|function|null=void):objectObject constructor.
assign(obj:object,...):objectReturn arg1 object with assigned values.
create(proto:null|object, properties:object=void):objectCreate a new object with prototype object and properties.
freeze(obj:object, freeze:boolean=true, modifyok:boolean=true, readcheck:boolean=true):object|voidFreeze/unfreeze an object with optionally.
getPrototypeOf(name:object|function):function|objectReturn prototype of an object.
hasOwnProperty(name:string):booleanReturns a true if object has the specified property.
is(value1, value2):booleanTests if two values are equal.
isPrototypeOf(name):booleanTests for an object in another object's prototype chain.
keys(obj:object|function|array):arrayReturn the keys of an object, array or function. Frozen empty objects will return getters.
merge(obj:object|function):objectReturn new object containing merged values.
propertyIsEnumerable(name):booleanDetermine if a property is enumerable.
setPrototypeOf(name:object, value:object)Set prototype of an object.
toLocaleString(quote:boolean=false):stringConvert to string.
toString(quote:boolean=false):stringConvert to string.
valueOf()Returns primitive value.
values(obj:object):arrayReturn the values of an object.

RegExp

Commands for managing reqular expression objects.

MethodFunction Argument TypesDescription
RegExp(val:regexp|string, flags:string):regexpCreate a regexp object.
exec(val:string):array|object|nullreturn matching string. Perform regexp match checking. Returns the array of matches.With the global flag g, sets lastIndex and returns next match.
test(val:string):booleantest if a string matches.

Signal

Commands for handling unix signals.

MethodFunction Argument TypesDescription
alarm(secs):numberSetup alarm in seconds.
callback(func:function, sig:number|string):numberSetup callback handler for signal.
handle(sig:number|string=void, ...)Set named signals to handle action.
ignore(sig:number|string=void, ...)Set named signals to ignore action.
kill(pid:number, sig:number|string='SIGTERM'):voidSend signal to process id.
names():arrayReturn names of all signals.
reset(sig:number|string=void, ...):arraySet named signals to default action.

Socket

Commands for managing Socket server/client connections.

MethodFunction Argument TypesDescription
Socket(options:object=void):userobjCreate socket server/client object.Create a socket server or client object.
close():voidClose socket(s).
conf(options:string|object=void)Configure options.
idconf(id:number=void, options:string|object=void)Configure options for a connection id, or return list of ids.
names():arrayReturn list of active ids on server.
recv(id:number=void):stringRecieve data.
send(id:number, data:string, options:object=void):voidSend a socket message to id. Send a message to a (or all if -1) connection.
update():voidService events for just this socket.

Socket new

OptionTypeDescriptionFlags
addressSTRINGClient destination address (127.0.0.0).initOnly
broadcastBOOLEnable broadcast.initOnly
clientBOOLEnable client mode.initOnly
connectCntINTCounter for number of active connections.readOnly
createLastTIME_TTime of last create.readOnly
debugINTDebugging level.
echoBOOLLogInfo outputs all socket Send/Recv messages.
interfaceSTRINGInterface for server to listen on, eg. 'eth0' or 'lo'.initOnly
keepaliveBOOLEnable keepalive.initOnly
maxConnectsINTIn server mode, max number of client connections accepted.
mcastAddMemberSTRINGMulticast add membership: address/interface ('127.0.0.1/0.0.0.0').initOnly
mcastInterfaceSTRINGMulticast interface address.initOnly
mcastNoLoopBOOLMulticast loopback disable.initOnly
mcastTtlINTMulticast TTL.initOnly
noAsyncBOOLSend is not async.initOnly
noUpdateBOOLStop processing update events (eg. to exit).
onCloseFUNCFunction to call when connection closes. @`function(s:userobjnull, id:number)`
onCloseLastFUNCFunction to call when last connection closes. On object delete arg is null. @`function(s:userobjnull)`
noConfigBOOLDisable use of Socket.conf to change options after create.initOnly
onOpenFUNCFunction to call when connection opens. @function(s:userobj, info:object)
onRecvFUNCFunction to call with recieved data. @function(s:userobj, id:number, data:string)
portINTPort for client dest or server listen.initOnly
quietBOOLSuppress info messages.initOnly
recvTimeoutUINT64Timeout for receive, in microseconds.initOnly
sendTimeoutUINT64Timeout for send, in microseconds.initOnly
srcAddressSTRINGClient source address.initOnly
srcPortINTClient source port.initOnly
startTimeTIME_TTime of start.readOnly
statsOptionsStatistical data.readOnly
timeoutNUMBERTimeout value in seconds (0.5).initOnly
tosINT8Type-Of-Service value.initOnly
ttlINTTime-To-Live value.initOnly
udataOBJUser data.
udpBOOLProtocol is udp.initOnly

Socket stats

OptionTypeDescriptionFlags
echoBOOLLogInfo outputs all socket Send/Recv messages.
eventCntINTNumber of events of any type.
eventLastTIME_TTime of last event of any type.
recvAddrCUSTOMIncoming port and address.
recvCntINTNumber of recieves.
recvLastTIME_TTime of last recv.
sentCntINTNumber of sends.
sentLastTIME_TTime of last send.
sentErrCntINTNumber of sends.
sentErrLastTIME_TTime of last sendErr.
udataOBJUser data.

Socket idconf

OptionTypeDescriptionFlags
echoBOOLLogInfo outputs all socket Send/Recv messages.
eventCntINTNumber of events of any type.
eventLastTIME_TTime of last event of any type.
recvAddrCUSTOMIncoming port and address.
recvCntINTNumber of recieves.
recvLastTIME_TTime of last recv.
sentCntINTNumber of sends.
sentLastTIME_TTime of last send.
sentErrCntINTNumber of sends.
sentErrLastTIME_TTime of last sendErr.
udataOBJUser data.

Socket send

OptionTypeDescriptionFlags
noAsyncBOOLSend is not async.

Sqlite

Commands for accessing sqlite databases.

MethodFunction Argument TypesDescription
Sqlite(file:null|string=void, options:object=void):userobjCreate a new db connection to the named file or :memory:.
backup(file:string, dbname:string='main'):voidBackup db to file. Open or create a database file named FILENAME. Transfer the content of local database DATABASE (default: 'main') into the FILENAME database.
collate(name:string, callback:function):voidCreate new SQL collation command.
complete(sql:string):booleanReturn true if sql is complete.
conf(options:string|object=void)Configure options.
eval(sql:string):numberRun sql commands without input/output. Supports multiple semicolon seperated commands. Variable binding is NOT performed, results are discarded, and returns sqlite3_changes()
exists(sql:string):booleanExecute sql, and return true if there is at least one result value.
filename(name:string='main'):stringReturn filename for named or all attached databases.
func(name:string, callback:function, numArgs:number=void):voidRegister a new function with database.
import(table:string, file:string, options:object=void):numberImport data from file into table . Import data from a file into table. SqlOptions include the 'separator' to use, which defaults to commas for csv, or tabs otherwise. If a column contains a null string, or the value of 'nullvalue', a null is inserted for the column. A 'conflict' is one of the sqlite conflict algorithms: rollback, abort, fail, ignore, replace On success, return the number of lines processed, not necessarily same as 'changeCnt' due to the conflict algorithm selected.
interrupt():voidInterrupt in progress statement.
onecolumn(sql:string)Execute sql, and return a single value.
query(sql:string, options:function|string|array|object=void)Evaluate an sql query with bindings. Return values in formatted as JSON, HTML, etc. , optionally calling function with a result object
restore(file:string, dbname:string):voidRestore db from file (default db is 'main'). db.restore(FILENAME, ?,DATABASE? ) Open a database file named FILENAME. Transfer the content of FILENAME into the local database DATABASE (default: 'main').
transaction(callback:function, type:string=void):voidCall function inside db tranasaction. Type is: 'deferred', 'exclusive', 'immediate'. Start a new transaction (if we are not already in the midst of a transaction) and execute the JS function FUNC. After FUNC completes, either commit the transaction or roll it back if FUNC throws an exception. Or if no new transation was started, do nothing. pass the exception on up the stack.

Sqlite new

OptionTypeDescriptionFlags
bindWarnBOOLTreat failed variable binds as a warning.initOnly
changeCntINTThe number of rows modified, inserted, or deleted by last command.
changeCntAllINTTotal number of rows modified, inserted, or deleted since db opened.
debugARRAYEnable debug trace for various operations. (zero or more of: eval, delete, prepare, step)
echoBOOLOutput query/eval string to log.
errCntINTCount of errors in script callbacks.readOnly
errorCodeINTNumeric error code returned by the most recent call to sqlite3_exec.
forceIntBOOLBind float as int if possible.
noJsonConvBOOLDo not JSON auto-convert array and object in CHARJSON columns.
lastInsertIdUINT64The rowid of last insert.
loadBOOLExtensions can be loaded.
maxRegexCacheINTMax cache size for regex patterns; 0=disable, -1=unlimited (100).
mutexSTRKEYMutex type to use. (one of: default, none, full)initOnly
nameDSTRINGThe dbname to use instead of 'main'.initOnly
noConfigBOOLDisable use of Sqlite.conf to change options after create.initOnly
noCreateBOOLDatabase is must already exist (false).initOnly
onAuthFUNCFunction to call for auth. @function(db:userobj, code:string, descr1:string, decr2:string, dbname:string, trigname:string)
onBusyFUNCFunction to call when busy. @function(db:userobj, tries:number)
onCommitFUNCFunction to call on commit. @function(db:userobj)
onNeedCollateFUNCFunction to call for collation. @function(db:userobj, name:string)
onProfileFUNCFunction to call for profile. @function(db:userobj, sql:string, time:number)
onProgressFUNCFunction to call for progress: progressSteps must be >0. @function(db:userobj)
onRollbackFUNCFunction to call for rollback. @function(db:userobj)
onTraceFUNCFunction to call for trace. @function(db:userobj, sql:string)
onUpdateFUNCFunction to call for update. @function(db:userobj, op:string, dbname:string, table:string, rowid:number)
onWalHookFUNCFunction to call for WAL. @function(db:userobj, dbname:string, entry:number)
progressStepsUINTNumber of steps between calling onProgress: 0 is disabled.
queryOptsOptionsDefault options for to use with query().
readonlyBOOLDatabase opened in readonly mode.initOnly
sortCntINTNumber of sorts in most recent operation.readOnly
stepCntINTNumber of steps in most recent operation.readOnly
stmtCacheCntINTCurrent size of compiled statement cache.readOnly
stmtCacheMaxINTMax cache size for compiled statements.
timeoutINTAmount of time to wait when file is locked, in ms.
udataOBJUser data.
versionOBJSqlite version info.readOnly
vfsSTRINGVFS to use.initOnly

Sqlite queryOpts

OptionTypeDescriptionFlags
callbackFUNCFunction to call with each row result. @function(values:object)
cdataSTRKEYName of Cdata array object to use.
echoBOOLOutput query string to log.
headersBOOLFirst row returned contains column labels.
limitINTMaximum number of returned values.
mapundefBOOLIn variable bind, map an 'undefined' var to null.
modeSTRKEYSet output mode of returned data. (one of: rows, arrays, array1d, list, column, json, json2, html, csv, insert, line, tabs, none)
nocacheBOOLDisable query cache.
nullvalueSTRKEYNull string output (for non js/json mode).
objOptionsOptions for object.
retChangedBOOLQuery returns value of sqlite3_changed().
separatorSTRKEYSeparator string (for csv and text mode).
typeCheckSTRKEYType check mode (warn). (one of: convert, warn, error, disable)
tableSTRKEYTable name for mode=insert.
valuesARRAYValues for ? bind parameters.
widthCUSTOMIn column mode, set column widths.

Sqlite obj

OptionTypeDescriptionFlags
nameSTRKEYName of object var data source for %s.
skipARRAYObject members to ignore.
getSqlBOOLReturn expanded SQL without evaluating.
defaultNullBOOLCreate with DEFAULT NULL.
noChecksBOOLCreate with no CHECK constraints.
noDefaultsBOOLCreate with no defaults.
noTypesBOOLCreate with no types.

Sqlite import

OptionTypeDescriptionFlags
headersBOOLFirst row contains column labels.
csvBOOLTreat input values as CSV.
conflictSTRKEYSet conflict resolution. (one of: ROLLBACK, ABORT, FAIL, IGNORE, REPLACE)
limitINTMaximum number of lines to load.
nullvalueSTRKEYNull string.
separatorSTRKEYSeparator string; default is comma if csv, else tabs.

Sqlite query

OptionTypeDescriptionFlags
callbackFUNCFunction to call with each row result. @function(values:object)
cdataSTRKEYName of Cdata array object to use.
echoBOOLOutput query string to log.
headersBOOLFirst row returned contains column labels.
limitINTMaximum number of returned values.
mapundefBOOLIn variable bind, map an 'undefined' var to null.
modeSTRKEYSet output mode of returned data. (one of: rows, arrays, array1d, list, column, json, json2, html, csv, insert, line, tabs, none)
nocacheBOOLDisable query cache.
nullvalueSTRKEYNull string output (for non js/json mode).
obj[Options](#Sqlite query-obj)Options for object.
retChangedBOOLQuery returns value of sqlite3_changed().
separatorSTRKEYSeparator string (for csv and text mode).
typeCheckSTRKEYType check mode (warn). (one of: convert, warn, error, disable)
tableSTRKEYTable name for mode=insert.
valuesARRAYValues for ? bind parameters.
widthCUSTOMIn column mode, set column widths.

Sqlite query obj

OptionTypeDescriptionFlags
nameSTRKEYName of object var data source for %s.
skipARRAYObject members to ignore.
getSqlBOOLReturn expanded SQL without evaluating.
defaultNullBOOLCreate with DEFAULT NULL.
noChecksBOOLCreate with no CHECK constraints.
noDefaultsBOOLCreate with no defaults.
noTypesBOOLCreate with no types.

String

Commands for accessing string objects..

MethodFunction Argument TypesDescription
String(str):stringString constructor.
charAt(index:number):stringReturn char at index.
charCodeAt(index:number):numberReturn char code at index.
concat(str:string, ...):stringAppend one or more strings.
fromCharCode(...):stringReturn string for char codes.
indexOf(str:string, start:number):numberReturn index of char.
lastIndexOf(str:string, start:number):numberReturn index of last char.
map(strMap:array, nocase:boolean=false):stringReplaces characters in string based on the key-value pairs in strMap.
match(pattern:regexp|string):array|nullReturn array of matches.
repeat(count:number):stringReturn count copies of string.
replace(pattern:regexp|string, replace:string|function):stringRegex/string replacement. If the replace argument is a function, it is called with match,p1,p2,...,offset,string. If called function is known to have 1 argument, it is called with just the match.
search(pattern:regexp|string):numberReturn index of first char matching pattern.
slice(start:number, end:number):stringReturn section of string.
split(char:string|null=void):arraySplit on char and return Array. When char is omitted splits on bytes. When char==null splits on whitespace and removes empty elements.
substr(start:number, length:number):stringReturn substring.
substring(start:number, end:number):stringReturn substring.
toLocaleLowerCase():stringLower case.
toLocaleUpperCase():stringUpper case.
toLowerCase():stringReturn lower cased string.
toTitle(chars:string):stringMake first char upper case.
toUpperCase():stringReturn upper cased string.
trim(chars:string):stringTrim chars.
trimLeft(chars:string):stringTrim chars from left.
trimRight(chars:string):stringTrim chars from right.

System

Builtin system commands. All methods are exported as global.

MethodFunction Argument TypesDescription
LogDebug(str:string|boolean,...):voidDebug logging command.
LogError(str:string|boolean,...):voidDebug logging command.
LogInfo(str:string|boolean,...):voidDebug logging command.
LogTest(str:string|boolean,...):voidDebug logging command.
LogTrace(str:string|boolean,...):voidDebug logging command.
LogWarn(str:string|boolean,...):voidDebug logging command.
assert(expr:boolean|number|function, msg:string=void, options:object=void):voidThrow or output msg if expr is false. Assertions. Enable with jsish --I Assert or using the -Assert module option.
clearInterval(id:number):voidDelete event id returned from setInterval/setTimeout/info.events().
decodeURI(val:string):stringDecode an HTTP URL.
decodeURIComponent(val:string):stringDecode an HTTP URL.
encodeURI(val:string):stringEncode an HTTP URL.
encodeURIComponent(val:string):stringEncode an HTTP URL.
exec(val:string, options:string|object=void)Execute an OS command. If the command ends with '&', set the 'bg' option to true. The second argument can be a string, which is the same as setting the 'inputStr' option. By default, returns the string output, unless the 'bg', 'inputStr', 'retCode' or 'retAll' options are used
exit(code:number=0):voidExit the current interpreter.
format(format:string, ...):stringPrintf style formatting: adds %q and %S.
getOpts(options:object, conf:object, self:object):objectGet options.
import(file:string, options:object=void)Same as source with {import:true}.
isFinite(val):booleanReturn true if is a finite number.
isMain():booleanReturn true if current script was the main script invoked from command-line.
isNaN(val):booleanReturn true if not a number.
load(shlib:string):voidLoad a shared executable and invoke its _Init call.
log(val, ...):voidSame as puts, but includes file:line.
matchObj(obj:object, match:string=void, partial=false, noerror=false):string|booleanValidate that object matches given name:type string. With single arg returns generated string.
module(cmd:string|function, version:number|string=1, options:object=void):voidSame as provide, but will invoke cmd if isMain is true.
moduleOpts(options:object, self:object|userobj=void, conf:object|null|undefined=void):objectParse module options.
moduleRun(cmd:string|function, args:array=undefined)Invoke named module with given args or command-line args.
noOp()A No-Op. A zero overhead command call that is useful for debugging.
parseFloat(val):numberConvert string to a double.
parseInt(val:any, base:number=10):numberConvert string to an integer.
printf(format:string, ...):voidFormatted output to stdout.
provide(cmd:string|function=void, version:number|string=1, options:object=void):voidMake a package available for use by require.
puts(val:any, ...):voidOutput one or more values to stdout. Each argument is quoted. Use Interp.logOpts to control source line and/or timestamps output.
quote(val:string):stringReturn quoted string.
require(name:string=void, version:number|string=1, options:object=void):number|array|objectLoad/query packages. With no arguments, returns the list of all loaded packages. With one argument, loads the package (if necessary) and returns its version. With two arguments, returns object containing: version, loadFile, func. A third argument sets options for package or module. Note an error is thrown if requested version is greater than actual version.
setInterval(callback:function, ms:number):numberSetup recurring function to run every given millisecs.
setTimeout(callback:function, ms:number):numberSetup function to run after given millisecs.
sleep(secs:number=1.0):voidsleep for N milliseconds, minimum .001.
source(val:string|array, options:object=void)Load and evaluate source files.
strftime(num:number=null, options:string|object=void):stringFormat numeric time (in ms) to string. Null or no value will use current time.
strptime(val:string=void, options:string|object=void):numberParse time from string and return ms time since 1970-01-01 in UTC, or NaN on error.
times(callback:function|boolean, count:number=1):numberCall function count times and return execution time in microseconds.
unload(shlib:string):voidUnload a shared executable and invoke its _Done call.
update(options:number|object=void):numberService all events, eg. setInterval/setTimeout. Returns the number of events processed. Events are processed until minTime (in milliseconds) is exceeded, or forever if -1. The default minTime is 0, meaning return as soon as no events can be processed. A positive mintime will result in sleeps between event checks.

System assert

OptionTypeDescriptionFlags
modeSTRKEYAction when assertion fails. Default from Interp.assertMode. (one of: log, puts, throw)
noStderrBOOLLogged msg to stdout. Default from Interp.noStderr.

System exec

OptionTypeDescriptionFlags
bgBOOLRun command in background using system() and return OS code.
chdirSTRINGChange to directory.
inputStrSTRINGUse string as input and return OS code.
noErrorBOOLSuppress all OS errors.
noRedirBOOLDisable redirect and shell escapes in command.
noShellBOOLDo not use native popen which invokes via /bin/sh.
trimBOOLTrim trailing whitespace from output.
retAllBOOLReturn the OS return code and data as an object.
retCodeBOOLReturn only the OS return code.

System import

OptionTypeDescriptionFlags
autoIndexBOOLLook for and load Jsi_Auto.jsi auto-index file.
existsBOOLSource file only if exists.
globalBOOLFile is to be sourced in global frame rather than local.
importBOOLWrap file contents in a return/function closure.
isMainBOOLCoerce to true the value of Info.isMain().
levelUINTFrame to source file in.
noEvalBOOLDisable eval: just parses file to check syntax.
noErrorBOOLIgnore errors in sourced file.
onceBOOLSource file only if not already sourced (Default: Interp.debugOpts.includeOnce).
traceBOOLTrace include statements (Default: Interp.debugOpts.includeTrace).

System module

OptionTypeDescriptionFlags
exitBOOLCall exit with return code after module run if isMain.
logARRAYLogging flags. (zero or more of: bug, assert, debug, trace, test, info, warn, error, parse)noCase
logmaskARRAYLogging mask flags. (zero or more of: bug, assert, debug, trace, test, info, warn, error, parse)noCase
coverageBOOLOn exit generate detailed code coverage for function calls (with profile).
nofreezeBOOLDisable moduleOpts freeze of first arg (self).
infoOBJInfo provided by module.initOnly
profileBOOLOn exit generate profile of function calls.
traceCallARRAYTrace commands. (zero or more of: funcs, cmds, new, return, args, notrunc, noparent, full, before)
udataOBJUser data settable by require.

System provide

OptionTypeDescriptionFlags
exitBOOLCall exit with return code after module run if isMain.
logARRAYLogging flags. (zero or more of: bug, assert, debug, trace, test, info, warn, error, parse)noCase
logmaskARRAYLogging mask flags. (zero or more of: bug, assert, debug, trace, test, info, warn, error, parse)noCase
coverageBOOLOn exit generate detailed code coverage for function calls (with profile).
nofreezeBOOLDisable moduleOpts freeze of first arg (self).
infoOBJInfo provided by module.initOnly
profileBOOLOn exit generate profile of function calls.
traceCallARRAYTrace commands. (zero or more of: funcs, cmds, new, return, args, notrunc, noparent, full, before)
udataOBJUser data settable by require.

System require

OptionTypeDescriptionFlags
exitBOOLCall exit with return code after module run if isMain.
logARRAYLogging flags. (zero or more of: bug, assert, debug, trace, test, info, warn, error, parse)noCase
logmaskARRAYLogging mask flags. (zero or more of: bug, assert, debug, trace, test, info, warn, error, parse)noCase
coverageBOOLOn exit generate detailed code coverage for function calls (with profile).
nofreezeBOOLDisable moduleOpts freeze of first arg (self).
infoOBJInfo provided by module.initOnly
profileBOOLOn exit generate profile of function calls.
traceCallARRAYTrace commands. (zero or more of: funcs, cmds, new, return, args, notrunc, noparent, full, before)
udataOBJUser data settable by require.

System source

OptionTypeDescriptionFlags
autoIndexBOOLLook for and load Jsi_Auto.jsi auto-index file.
existsBOOLSource file only if exists.
globalBOOLFile is to be sourced in global frame rather than local.
importBOOLWrap file contents in a return/function closure.
isMainBOOLCoerce to true the value of Info.isMain().
levelUINTFrame to source file in.
noEvalBOOLDisable eval: just parses file to check syntax.
noErrorBOOLIgnore errors in sourced file.
onceBOOLSource file only if not already sourced (Default: Interp.debugOpts.includeOnce).
traceBOOLTrace include statements (Default: Interp.debugOpts.includeTrace).

System strftime

OptionTypeDescriptionFlags
secsBOOLTime is seconds (out for parse, in for format).
fmtSTRKEYFormat string for time.
isoBOOLISO fmt plus milliseconds ie: %FT%T.%f.
utcBOOLTime is utc (in for parse, out for format).

System strptime

OptionTypeDescriptionFlags
secsBOOLTime is seconds (out for parse, in for format).
fmtSTRKEYFormat string for time.
isoBOOLISO fmt plus milliseconds ie: %FT%T.%f.
utcBOOLTime is utc (in for parse, out for format).

System update

OptionTypeDescriptionFlags
maxEventsINTMaximum number of events to process (or -1 for all).
maxPassesINTMaximum passes through event queue.
minTimeINTMinimum milliseconds before returning, or -1 to loop forever (default is 0).
sleepINTTime to sleep time (in milliseconds) between event checks. Default is 1.

Util

Utilities commands.

MethodFunction Argument TypesDescription
argArray(arg:any|undefined):array|nullCoerces non-null to an array, if necessary.
base64(val:string, decode:boolean=false):stringBase64 encode/decode a string.
complete(val:string):booleanReturn true if string is complete command with balanced braces, etc.
crc32(val:string, crcSeed=0):numberCalculate 32-bit CRC.
dbgAdd(val:string|number, temp:boolean=false):numberDebugger add a breakpoint for line, file:line or func.
dbgEnable(id:number, on:boolean):voidDebugger enable/disable breakpoint.
dbgInfo(id:number=void):array|objectDebugger return info about one breakpoint, or list of bp numbers.
dbgRemove(id:number):voidDebugger remove breakpoint.
decrypt(val:string, key:string):stringDecrypt data using BTEA encryption. Keys that are not 16 bytes use the MD5 hash of the key.
encrypt(val:string, key:string):stringEncrypt data using BTEA encryption. Keys that are not 16 bytes use the MD5 hash of the key.
fromCharCode(code:number):stringReturn char with given character code.
getenv(name:string=void):string|object|voidGet one or all environment.
getpid(parent:boolean=false):numberGet process/parent id.
getuser():objectGet userid info.
hash(val:string, options:object=void):stringReturn hash (default SHA256) of string/file.
hexStr(val:string, decode:boolean=false):stringHex encode/decode a string.
setenv(name:string, value:string=void)Set/get an environment var.
sqlValues(name:string, obj:object=void)Get object values for SQL.
times(callback:function|boolean, count:number=1):numberCall function count times and return execution time in microseconds.
verConvert(ver:string|number, zeroTrim:number=0):number|string|nullConvert a version to/from a string/number, or return null if not a version. For string output zeroTrim says how many trailing .0 to trim (0-2).
vueConvert(fn:string,data:string|null=void):stringConvert/generate .vue/.js file; returns a %s fmt string when data=null.

Util hash

OptionTypeDescriptionFlags
fileSTRINGRead data from file and append to str.
hashcashUINTSearch for a hash with this many leading zero bits by appending :nonce (Proof-Of-Work).
noHexBOOLReturn binary digest, without conversion to hex chars.
typeSTRKEYType of hash. (one of: sha256, sha1, md5, sha3_224, sha3_384, sha3_512, sha3_256)

Vfs

Commands for creating in memory readonly Virtual file-systems.

MethodFunction Argument TypesDescription
conf(mount:string, options:string|object|string=void)Configure mount.
exec(cmd:string)Safe mode exec for VFS support cmds eg. fossil info/ls/cat.
fileconf(mount:string, path:string, options:string|object=void)Configure file info which is same info as in fileList.
list():arrayReturn list of all vfs mounts.
mount(type:string, file:string, param:object=void):stringMount fossil file as given VFS type name, returning the mount point: frontend for vmount.
type(type:string=void, options:object|null=void)Set/get/delete VFS type name.
unmount(mount:string):voidUnmount a VFS.
vmount(options:object=void):stringCreate and mount a VFS, returning the mount point.

Vfs conf

OptionTypeDescriptionFlags
callbackFUNCFunction implementing VFS. @`function(op:string, mount:string, arg:stringobject
extraOBJExtra info, typically used by predefined VFS type.
noAddDirsBOOLDisable auto-adding of directories; needed by File.glob.
fileSTRINGFossil file to mount.
fileListARRAYList of files in the VFS (from listFunc).
infoOBJInfo for VFS that is stored upon init.
mountSTRINGMount point for the VFS.
noPatchesBOOLIgnore patchlevel updates: accepts only X.Y releases.
paramOBJOptional 3rd argument passed to mount.
typeSTRKEYType for predefined VFS.
userOBJUser data.
versionSTRKEYVersion to mount.

Vfs exec

OptionTypeDescriptionFlags
dataSTRINGData for file.
fileSTRKEYFile pathname.required
permsUINT32Permissions for file.
sizeSSIZE_TSize of file.
timestampTIME_TTimestamp of file.

Vfs fileconf

OptionTypeDescriptionFlags
dataSTRINGData for file.
fileSTRKEYFile pathname.required
permsUINT32Permissions for file.
sizeSSIZE_TSize of file.
timestampTIME_TTimestamp of file.

Vfs type

OptionTypeDescriptionFlags
callbackFUNCFunction implementing VFS. @`function(op:string, mount:string, arg:stringobject
extraOBJExtra info, typically used by predefined VFS type.
noAddDirsBOOLDisable auto-adding of directories; needed by File.glob.

Vfs vmount

OptionTypeDescriptionFlags
callbackFUNCFunction implementing VFS. @`function(op:string, mount:string, arg:stringobject
extraOBJExtra info, typically used by predefined VFS type.
noAddDirsBOOLDisable auto-adding of directories; needed by File.glob.
fileSTRINGFossil file to mount.
fileListARRAYList of files in the VFS (from listFunc).
infoOBJInfo for VFS that is stored upon init.
mountSTRINGMount point for the VFS.
noPatchesBOOLIgnore patchlevel updates: accepts only X.Y releases.
paramOBJOptional 3rd argument passed to mount.
typeSTRKEYType for predefined VFS.
userOBJUser data.
versionSTRKEYVersion to mount.

WebSocket

Commands for managing WebSocket server/client connections.

MethodFunction Argument TypesDescription
WebSocket(options:object=void):userobjCreate websocket server/client object.Create a websocket server/client object. The server serves out pages to a web browser, which can use javascript to upgrade connection to a bidirectional websocket.
conf(options:string|object=void)Configure options.
file(name:string=void):array|voidAdd file to hash, or with no args return file hash.
handler(extension:string=void, cmd:string|function=void, flags:number=0):string|array|function|voidGet/Set handler command for an extension. With no args, returns list of handlers. With one arg, returns value for that handler. Otherwise, sets the handler. When cmd is a string, the call is via moduleRun([cmd], arg). If a cmd is a function, it is called with a single arg: the file name.
header(id:number, name:string=void):string|array|voidGet one or all input headers for connect id.
idconf(id:number, options:string|object=void)Configure options for connect id.
ids(name:string=void):arrayReturn list of ids, or lookup one id.
query(id:number, name:string=void):string|object|voidGet one or all query values for connect id.
send(id:number, data:any):voidSend a websocket message to id. Send a message to one (or all connections if -1). If not already a string, msg is formatted as JSON prior to the send.
status():object|voidReturn liblws server status.
unalias(path:string):string|voidLookup name-key with the given path in pathAlias object.
update():voidService events for just this websocket.
version():stringRuntime library version string.

WebSocket new

OptionTypeDescriptionFlags
addressSTRINGIn client-mode the address to connect to (127.0.0.1).
bufferPwr2INTTune the recv/send buffer: value is a power of 2 in [0-20] (16).
clientBOOLRun in client mode.initOnly
clientHostSTRKEYOverride host name for client.
clientOriginSTRKEYOverride client origin (origin).
debugINTSet debug level. Setting this to 512 will turn on max liblws log levels.
dirIndexSTRKEYEnable listing directories. (one of: auto, html, json, jsonp, disabled)
echoBOOLLogInfo outputs all websock Send/Recv messages.
formParamsSTRKEYComma seperated list of upload form param names ('text,send,file,upload').readOnly
extHandlersBOOLSetup builtin extension-handlers, ie: .htmli, .cssi, .jsi, .mdi.initOnly
extOptsOBJKey/value store for extension-handlers options.initOnly
flagsINTFlags for future use..
getRegexpREGEXPCall onGet() only if Url matches pattern.
headersARRAYHeaders to send to browser: name/value pairs.initOnly
jsiFnPatternSTRKEYA glob-match pattern for files to which is appended 'window.jsiWebSocket=true;' (jsi_config*.js).readOnly
interfaceSTRINGInterface for server to listen on, eg. 'eth0' or 'lo'.initOnly
localBOOLLimit connections to localhost addresses on the 127 network.
localhostNameSTRKEYClient name used by localhost connections ('localhost').
maxConnectsINTIn server mode, max number of client connections accepted.
maxDownloadINTMax size of file download.
maxUploadINTMax size of file upload will accept.
mimeTypesOBJObject map of file-exts to mime types; initial and/or override of builtins.
mimeLookupFuncFUNCFunction to call to lookup mime; returns and/or inserts into mimeTypes. @function(ws:userobj, id:number, extension:string, url:string)
modifySecsUINTSeconds between checking for modified files with onModify (2).
noConfigBOOLDisable use of conf() to change options after options after create.initOnly
noCompressBOOLDisable per-message-deflate extension which can truncate large msgs.
noUpdateBOOLDisable update event-processing.
noWebsockBOOLServe html, but disallow websocket upgrade.initOnly
noWarnBOOLQuietly ignore file related errors.
onAuthFUNCFunction to call for http basic authentication. @function(ws:userobj, id:number, url:string, userpass:string)
onCloseFUNCFunction to call when the websocket connection closes. @`function(ws:userobjnull, id:number, isError:boolean)`
onCloseLastFUNCFunction to call when last websock connection closes. On object delete arg is null. @`function(ws:userobjnull)`
onFilterFUNCFunction to call on a new connection: return false to kill connection. @function(ws:userobj, id:number, url:string, ishttp:boolean)
onGetFUNCFunction to call to server handle http-get. @function(ws:userobj, id:number, url:string, query:array)
onModifyFUNCFunction to call when a served-out-file is modified. @function(ws:userobj, file:string)initOnly
onOpenFUNCFunction to call when the websocket connection occurs. @function(ws:userobj, id:number)
onUnknownFUNCFunction to call to server out content when no file exists. @function(ws:userobj, id:number, url:string, query:array)
onUploadFUNCFunction to call handle http-post. @function(ws:userobj, id:number, filename:string, data:string, startpos:number, complete:boolean)
onRecvFUNCFunction to call when websock data recieved. @function(ws:userobj, id:number, data:string)
pathAliasesOBJAlias document root ({jsi:'/zvfs/lib/www'}) .initOnly
pollmsINTPoll wait time in ms (5).
portINTPort for server to listen on (8080).initOnly
postSTRINGPost string to serve.initOnly
protocolSTRKEYName of protocol (ws/wss).
realmSTRKEYRealm for basic auth (jsish).
recvBufMaxINTSize limit of a websocket message.initOnly
recvBufTimeoutINTTimeout for recv of a websock msg.initOnly
redirMaxBOOLTemporarily disable redirects when see more than this in 10 minutes.
rootdirSTRINGDirectory to serve html from (".").
serverSTRKEYString to send out int the header SERVER (jsiWebSocket).
sessFlagINTFlag to send in sessionJsi cookie.initOnly
ssiExtsOBJObject map of file extensions to apply SSI. eg. {myext:true, shtml:false} .initOnly
sslBOOLUse https.initOnly
sslCertSTRKEYSSL certificate file.
sslKeySTRKEYSSL key file.
statsOptionsStatistical data.readOnly
startTimeTIME_TTime of websocket start.readOnly
includeFileSTRKEYDefault file when no extension given (include.shtml).
udataOBJUser data.
urlFallbackSTRKEYFallback to serve when file not found..
urlPrefixSTRKEYPrefix in url to strip from path; for reverse proxy..
urlRedirectSTRKEYRedirect when no url or /, and adds cookie sessionJsi..
urlUnknownSTRKEYRedirect for 404 unknown page..
useridPassSTRKEYThe USERID:PASSWORD to use for basic authentication.
versionOBJWebSocket version info.readOnly
vueCvtBOOLConvert .vue rewrite enable.
vueES6BOOLUse ES6 export for .vue rewrite.

WebSocket stats

OptionTypeDescriptionFlags
connectCntINTNumber of active connections.readOnly
createTimeTIME_TTime created.
eventCntINTNumber of events of any type.
eventLastTIME_TTime of last event of any type.
httpCntINTNumber of http reqs.
httpLastTIME_TTime of last http reqs.
isBinaryBOOLConnection recv data is binary.readOnly
isFinalBOOLFinal data for current message was recieved.readOnly
msgQLenINTNumber of messages in input queue.readOnly
recvCntINTNumber of recieves.readOnly
recvLastTIME_TTime of last recv.readOnly
redirLastTIME_TTime of last redirect.readOnly
redirCntINTCount of redirects.readOnly
sentCntINTNumber of sends.readOnly
sentLastTIME_TTime of last send.readOnly
sentErrCntINTNumber of sends.readOnly
sentErrLastTIME_TTime of last sendErr.readOnly
sentErrLastTIME_TTime of last sendErr.readOnly
uploadCntINTNumber of uploads.readOnly
uploadEndTIME_TTime of upload end.readOnly
uploadLastTIME_TTime of last upload input.readOnly
uploadStartTIME_TTime of upload start.readOnly

WebSocket idconf

OptionTypeDescriptionFlags
clientIPSTRKEYClient IP Address.readOnly
clientNameSTRKEYClient hostname.readOnly
echoBOOLLogInfo outputs all websock Send/Recv messages.
headersARRAYHeaders to send to browser on connection: name/value pairs.
isWebsockBOOLIs a websocket connection.
keySTRBUFString key lookup in ids command for SSI echo ${#}.readOnly
onCloseFUNCFunction to call when the websocket connection closes. @`function(ws:userobjnull, id:number, isError:boolean)`
onGetFUNCFunction to call to server handle http-get. @function(ws:userobj, id:number, url:string, query:array)
onUnknownFUNCFunction to call to serve out content when no file exists. @function(ws:userobj, id:number, url:string, args:array)
onRecvFUNCFunction to call when websock data recieved. @function(ws:userobj, id:number, data:string)
onUploadFUNCFunction to call handle http-post. @function(ws:userobj, id:number, filename:string, data:string, startpos:number, complete:boolean)
rootdirSTRINGDirectory to serve html from (".").
stats[Options](#WebSocket idconf-stats)Statistics for connection.readOnly
queryARRAYUri arg values for connection.
queryObjOBJUri arg values for connection as an object.
udataOBJUser data.
urlDSTRINGUrl for connection.
usernameSTRINGThe login userid for this connection.

WebSocket idconf stats

OptionTypeDescriptionFlags
connectCntINTNumber of active connections.readOnly
createTimeTIME_TTime created.
eventCntINTNumber of events of any type.
eventLastTIME_TTime of last event of any type.
httpCntINTNumber of http reqs.
httpLastTIME_TTime of last http reqs.
isBinaryBOOLConnection recv data is binary.readOnly
isFinalBOOLFinal data for current message was recieved.readOnly
msgQLenINTNumber of messages in input queue.readOnly
recvCntINTNumber of recieves.readOnly
recvLastTIME_TTime of last recv.readOnly
redirLastTIME_TTime of last redirect.readOnly
redirCntINTCount of redirects.readOnly
sentCntINTNumber of sends.readOnly
sentLastTIME_TTime of last send.readOnly
sentErrCntINTNumber of sends.readOnly
sentErrLastTIME_TTime of last sendErr.readOnly
sentErrLastTIME_TTime of last sendErr.readOnly
uploadCntINTNumber of uploads.readOnly
uploadEndTIME_TTime of upload end.readOnly
uploadLastTIME_TTime of last upload input.readOnly
uploadStartTIME_TTime of upload start.readOnly

Zvfs

Commands for mounting and accessing .zip files as a filesystem.

MethodFunction Argument TypesDescription
append(archive:string, filelist:array, path:string|null=void, filelist2:array=void, path2:string|null=void, ...):voidLike 'create()', but appends to an existing archive (with no dup checking).
create(archive:string, filelist:array, path:string|null=void, filelist2:array=void, path2:string|null=void, ...):voidCreate a zip with the given files in prefix path. This command creates a zip archive and adds files to it. Files are relative the given 'path', or the current directory. If the destignation file already exist but is not an archive (eg. an executable), zip data is appended to the end of the file. If the existing file is already an archive, an error will be thrown. To truncate an existing archive, use zvfs.truncate(). Or use zvfs.append() instead. zvfs.create('foo.zip',['main.js', 'bar.js'], 'src', ['a.html', 'css/a.css'], 'html');
deflate(data:string):stringCompress string using zlib deflate.
inflate(data:string):stringUncompress string using zlib inflate.
list(archive:string=void):arrayList files in archive. Return contents of zip directory as an array of arrays. The first element contains the labels, ie: [ 'Name', 'Special', 'Offset', 'Bytes', 'BytesCompressed' ]
mount(archive:string, mountdir:string=void):stringMount zip on mount point. Read a ZIP archive and make entries in the virutal file hash table for all files contained therein.
names(mountdir:string=void):arrayReturn all zvfs mounted zips, or archive for specified mount. Given an mount point argument, returns the archive for it. Otherwise, returns an array of mount points
offset(archive:string=void):numberReturn the start offset of zip data. Opens and scans the file to determine start of zip data and truncate this off the end of the file. For ordinary zip archives, the resulting truncated file will be of zero length. If an optional bool argument can disable errors. In any case, the start offset of zip data (or 0) is returned.
stat(filename:string):objectReturn details on file in zvfs mount. Return details about the given file in the ZVFS. The information consists of (1) the name of the ZIP archive that contains the file, (2) the size of the file after decompressions, (3) the compressed size of the file, and (4) the offset of the compressed data in the archive.
truncate(archive:string, noerror:boolean=false):numberTruncate zip data from archive. Opens and scans the file to determine start of zip data and truncate this off the end of the file. For ordinary zip archives, the resulting truncated file will be of zero length. If an optional bool argument can disable errors. In any case, the start offset of zip data (or 0) is returned.
unmount(archive:string):voidUnmount zip.

console

Console input and output to stderr.

MethodFunction Argument TypesDescription
assert(expr:boolean|number|function, msg:string=void, options:object=void):voidSame as System.assert().
error(val, ...):voidSame as log but adding prefix ERROR:.
input(prompt:null|string=''):string|voidRead input from the console: if prompt uses linenoise line editing.
log(val, ...):voidLike System.puts, but goes to stderr and includes file:line.
logp(val, ...):voidSame as console.log, but first arg is string prefix and if second is a boolean it controls output.
printf(format:string, ...):voidSame as System.printf but goes to stderr.
puts(val:any, ...):voidSame as System.puts, but goes to stderr.
warn(val, ...):voidSame as log.

console assert

OptionTypeDescriptionFlags
modeSTRKEYAction when assertion fails. Default from Interp.assertMode. (one of: log, puts, throw)
noStderrBOOLLogged msg to stdout. Default from Interp.noStderr.