jsish
Reference
Not logged in

Builtin command reference. See System for global commands. (Related: Functions, Syntax).

Array Boolean CData CEnum CStruct CType Channel Debug Event File Function Info Interp JSON Math MySql Number Object RegExp Signal Socket Sqlite String System Util Vfs WebSocket Zvfs console


Array

Synopsis:new Array(...):array

Provide access to array objects.

Methods for "Array"

MethodPrototypeDescription
Arraynew Array(...):array Array constructor.
concatconcat(...):array Return array with args appended.
everyevery(callback:function) Returns true if every value in array satisfies the test.
fillfill(value:any, start:number=0, end:number=-1):array Fill an array with values.
filterfilter(callback:function, this:object=void):array Return a filtered array.
findfind(callback:function) Returns the value of the first element in the array that satisfies the test.
findIndexfindIndex(callback:function) Returns the index of the first element in the array that satisfies the test.
forEachforEach(callback:function, this:object=void):undefined Invoke function with each item in object.
includesincludes(val:any) Returns true if array contains value.
indexOfindexOf(str:any, startIdx:number=0):number Return index of first occurrance in array.
isArrayisArray(val:any):boolean True if val array.
joinjoin(sep:string=''):string Return elements joined by char.
lastIndexOflastIndexOf(val:any, start:number=0):number Return index of last occurence in array.
mapmap(callback:function, this:object=void):array Creates a new array with the results of calling a provided function on every element in this array.
poppop() Remove and return last element of array.
pushpush(val:any, ...):number Push one or more elements onto array and return size.
reversereverse():array Reverse order of all elements in an array.
shiftshift() Remove first element and shift downwards.
sizeOfsizeOf():number Return size of array.
sliceslice(start:number, end:number=void):array Return sub-array.
somesome(callback:function, this:object=void):boolean Return true if function returns true some element.
sortsort(options:function|object=void):array Sort an array.
splicesplice(start:number, howmany:number=void, ...):array Change the content of an array, adding new elements while removing old elements.
unshiftunshift(...):number Add new elements to start of array and return size.

Options for "Array.sort"

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

Return to top


Boolean

Synopsis:new Boolean(bool:boolean=false):boolean

A Boolean object.

Methods for "Boolean"

MethodPrototypeDescription
Booleannew Boolean(bool:boolean=false):boolean Boolean constructor.

Return to top


CData

Synopsis:new CData(options:string|object=void):userobj

Methods for "CData"

MethodPrototypeDescription
CDatanew CData(options:string|object=void):userobj Create a new struct or map/array of structs.
confconf(options:object|string=void) Configure options for c-data.
getget(key:string|number|object|null, field:string=void) Get struct/map/array value.
incrincr(key:string|number|object|null, field:object|string, value:number):number Increment a numeric field: returns the new value.
infoinfo():object Return info for data.
namesnames():array Return keys for map.
setset(key:string|number|object|null, field:object|string, value:any=void) Set a struct/map/array value.
unsetunset(key:string|number|object) Remove entry from map/array.

Options for "new CData"

Option Type DescriptionFlags
arrSizeUINTIf an array, its size in elements.initOnly
flagsUINTFlags.initOnly
helpSTRKEYDescription of data.initOnly
keyNameSTRKEYKey struct, for key struct maps.initOnly
keyTypeSTRKEYKey id. (one of: string, strkey, number)initOnly
mapTypeSTRKEYIf a map, its type. (one of: none, hash, tree, list)initOnly
maxSizeUINTLimit the array size or number of keys in a map.
nameSTRKEYName (eg. of var assigned to on create).initOnly
noAutoBOOLDisable auto-create of map keys in set/incr.
structNameSTRKEYStruct used for storing data.initOnly|required
userINT64User data.
varParamSTRKEYParam for maps/array vars.initOnly

Return to top


CEnum

Synopsis:CEnum.method(...)

Enum commands.

Methods for "CEnum"

MethodPrototypeDescription
confconf(enum:string, options:object|string=void) Configure options for enum.
definedefine(options:object|string, fields:array|string) Create an enum: value of items same as in fieldconf.
fieldconffieldconf(enum:string, field:string, options:object|string=void) Configure options for fields.
findfind(enum:string, intValue:number):string Find item with given value in enum.
getget(enum:string):object Return enum definition.
namesnames(enum:string=void):array Return name list of all enums, or items within one enum.
undefundef(enum:string) Remove an enum.
valuevalue(enum:string, item:string):number Return value for given enum item.

Options for "CEnum.conf"

Option Type DescriptionFlags
flagsINT64Flags for enum.initOnly
helpSTRKEYDescription of enum.initOnly
nameSTRKEYName of enum.initOnly
idxUINTNumber of items in enum.readOnly

Options for "CEnum.define"

Option Type DescriptionFlags
flagsINT64Flags for enum.initOnly
helpSTRKEYDescription of enum.initOnly
nameSTRKEYName of enum.initOnly
idxUINTNumber of items in enum.readOnly

Options for "CEnum.fieldconf"

Option Type DescriptionFlags
flagsINT64Flags for item.initOnly
helpSTRKEYDesciption of item.initOnly
nameSTRKEYName of item.initOnly
valueINT64Value for item.initOnly
idxUINTIndex of item in enum.readOnly

Return to top


CStruct

Synopsis:CStruct.method(...)

Methods for "CStruct"

MethodPrototypeDescription
confconf(struct:string, options:object|string=void) Configure options for struct.
definedefine(options:object|string, fields:array|string) Create a struct: field values same as in fieldconf.
fieldconffieldconf(struct:string, field:string, options:object|string=void) Configure options for fields.
getget(struct, options:object=void):object Return the struct definition.
namesnames(struct:string=void):array Return name list of all structs, or fields for one struct.
schemaschema():string Return database schema for struct.
undefundef(name:string) Remove a struct.

Options for "CStruct.conf"

Option Type DescriptionFlags
crcUINT32Crc for struct.initOnly
flagsINT64Flags for struct.initOnly
helpSTRKEYStruct description.initOnly
idxUINT32Number of fields in struct.readOnly
nameSTRKEYName of struct.initOnly|required
sizeUINTSize of struct in bytes.readOnly
ssigUINT32Signature for struct.initOnly
valueINT64Reference count.readOnly

Options for "CStruct.define"

Option Type DescriptionFlags
crcUINT32Crc for struct.initOnly
flagsINT64Flags for struct.initOnly
helpSTRKEYStruct description.initOnly
idxUINT32Number of fields in struct.readOnly
nameSTRKEYName of struct.initOnly|required
sizeUINTSize of struct in bytes.readOnly
ssigUINT32Signature for struct.initOnly
valueINT64Reference count.readOnly

Options for "CStruct.fieldconf"

Option Type DescriptionFlags
arrSizeUINTSize of field if an array?.initOnly
bitsUINT32Size of bitfield.initOnly
boffsetUINT32Bit offset of field within struct.readOnly
flagsINT64Flags for field.initOnly
idxUINT32Index of field in struct.readOnly
helpSTRKEYField description.initOnly
infoSTRKEYInfo for field.initOnly
nameSTRKEYName of field.initOnly|required
offsetUINTOffset of field within struct.readOnly
sizeUINTSize of field in struct.readOnly
typeCUSTOMType of field.initOnly|required
initCUSTOMInitial value for field.initOnly

Return to top


CType

Synopsis:CType.method(...)

Methods for "CType"

MethodPrototypeDescription
confconf(typ:string, options:object|string=void) Configure options for type.
namesnames(ctype=false):array Return type names.

Options for "CType.conf"

Option Type DescriptionFlags
idNameSTRKEYThe id name: usually upcased cName.initOnly
cNameSTRKEYC type name.initOnly
helpSTRKEYDescription of id.initOnly
fmtSTRKEYPrintf format for id.initOnly
xfmtSTRKEYHex printf format for id.initOnly
flagsINT64Flags for id.initOnly
sizeINTSize for id.initOnly
userINT64User data.

Return to top


Channel

Synopsis:new Channel(file:string, mode:string='r'):userobj

Commands for accessing Channel objects for file IO.

Methods for "Channel"

MethodPrototypeDescription
Channelnew Channel(file:string, mode:string='r'):userobj A file input/output object. The mode string is r or w and an optional +.
closeclose():boolean Close the file.
eofeof():boolean Return true if read to end-of-file.
filenamefilename():string Get file name.
flushflush():number Flush file output.
getsgets():string|undefined Get one line of input.
lstatlstat():object Return status for file.
modemode():string Get file mode used with open.
openopen(file:string, mode:string='r'):boolean Open the file (after close).
putsputs(str):boolean Write one line of output.
readread(size:number=-1):string|undefined Read some or all of file.
seekseek(pos:number, whence:string):number Seek to position. Return 0 if ok.
statstat():object Return status for file.
telltell():number Return current position.
truncatetruncate(pos:number):number Truncate file.
writewrite(data):number Write data to file.

Return to top


Debug

Synopsis:Debug.method(...)

Debugging management.

Methods for "Debug"

MethodPrototypeDescription
addadd(val:string|number, temp:boolean=false):number Add a breakpoint for line, file:line or func.
enableenable(id:number, on:boolean):void Enable/disable breakpoint.
infoinfo(id:number=void):array|object Return info about one breakpoint, or list of bp numbers.
removeremove(id:number):void Remove breakpoint.

Return to top


Event

Synopsis:Event.method(...)

Event management.

Methods for "Event"

MethodPrototypeDescription
clearIntervalclearInterval(id:number):void Delete an event (created with setInterval/setTimeout).
infoinfo(id:number):object Return info for the given event id.
namesnames():array Return list event ids (created with setTimeout/setInterval).
setIntervalsetInterval(callback:function, millisecs:number):number Setup recurring function to run every given millisecs.
setTimeoutsetTimeout(callback:function, millisecs:number):number Setup function to run after given millisecs.
updateupdate(options:number|object=void):number Service 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.

Options for "Event.update"

Option Type DescriptionFlags
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.

Return to top


File

Synopsis:File.method(...)

Commands for accessing the filesystem.

Methods for "File"

MethodPrototypeDescription
atimeatime(file:string):number Return file Jsi_Access time.
chdirchdir(file:string) Change current directory.
chmodchmod(file:string, mode:string) Set file permissions.
copycopy(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.
dirnamedirname(file:string):string Return directory path.
executableexecutable(file:string):boolean Return true if file is executable.
existsexists(file:string):boolean Return true if file exists.
extensionextension(file:string):string Return file extension.
globglob(pattern:regexp|string|null='*', options:function|object|null=void):array Return 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 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 arugment must be a set of options.
isdirisdir(file:string):boolean Return true if file is a directory.
isfileisfile(file:string):boolean Return true if file is a normal file.
isrelativeisrelative(file:string):boolean Return true if file path is relative.
joinjoin(path:string, path:string):string Join two file realpaths, or just second if an absolute path.
linklink(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.
lstatlstat(file:string):object Return status info for file.
mkdirmkdir(file:string) Create a directory.
mtimemtime(file:string):number Return file modified time.
ownedowned(file:string):boolean Return true if file is owned by user.
pwdpwd():string Return current directory.
readread(file:string, mode:string='rb'):string Read a file.
readablereadable(file:string):boolean Return true if file is readable.
readlinkreadlink(file:string):string Read file link destination.
realpathrealpath(file:string):string Return absolute file name minus .., ./ etc.
removeremove(file:string, force:boolean=false) Delete a file or direcotry.
renamerename(src:string, dest:string, force:boolean=false) Rename a file, with possible overwrite.
rootnamerootname(file:string):string Return file name minus extension.
sizesize(file:string):number Return size for file.
statstat(file:string):object Return status info for file.
tailtail(file:string):string Return file name minus dirname.
tempfiletempfile(file:string) Create a temp file.
truncatetruncate(file:string, size:number) Truncate file.
typetype(file:string):string Return type of file.
writablewritable(file:string):boolean Return true if file is writable.
writewrite(file:string, str:string, mode:string='wb+'):number Write a file.

Options for "File.glob"

Option Type DescriptionFlags
dirVALUEThe start directory: this path will not be prepended to results.
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.
noTypesSTRKEYFilter files to exclude these "types".
prefixSTRKEYString prefix to add to each file in list.
recurseBOOLRecurse into sub-directories.
retCountBOOLReturn only the count of matches.
tailsBOOLReturned only tail of path.
typesSTRKEYFilter files to include type: one or more of chars 'fdlpsbc' for file, directory, link, etc.

Return to top


Function

Synopsis:new Function():function

Commands for accessing functions.

Methods for "Function"

MethodPrototypeDescription
Functionnew Function():function Function constructor (unimplemented).
applyapply(thisArg:null|object, args:array=void) Call function passing args array.
bindbind(thisArg:object=null,arg,...) Return function that calls bound function prepended with thisArg+arguments.
callcall(thisArg:null|object, arg1, ...) Call function with args.

Return to top


Info

Synopsis:Info.method(...)

Commands for inspecting internal state information in JSI.

Methods for "Info"

MethodPrototypeDescription
argv0argv0():string|void Return initial start script file name.
cmdscmds(val:string|regexp='*', options:object=void):array|object Return details or list of matching commands.
completionscompletions(str:string, start:number=0, end:number=void):array Return command completions on portion of string from start to end.
datadata(val:string|regexp|object=void):array Return list of matching data (non-functions). Like info.vars(), but does not return function values.
errorerror():object Return file and line number of error (used inside catch).
eventevent(id:number=void):array|object List 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.
execZipexecZip():string|void If executing a .zip file, return file name.
executableexecutable():string Return name of executable.
filesfiles():array Return list of all sourced files.
funcsfuncs(string|regexp|object=void):array|object Return details or list of matching functions.
interpinterp(interp:userobj=void):object Return info on given or current interp.
isMainisMain():boolean Return true if current script was the main script invoked from command-line.
keywordskeywords():array Return list of reserved jsi keywords.
levellevel(level:number=void):number|array|object Return 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.
lookuplookup(name:string) Given string name, lookup and return value (eg. function).
methodsmethods(val:string|regexp):array|object Return functions and commands.
namednamed(name:string=void):array|userobj Returns command names for builtin Objects (eg. 'File', 'Interp'), sub-Object names, or the named object.
optionsoptions(ctype:boolean=false):array Return Option type name, or with true the C type).
platformplatform():object N/A. Returns general platform information for JSI.
scriptscript(func:function|regexp=void):string|array|void Get current script file name, or file containing function.
scriptDirscriptDir():string|void Get directory of current script.
varsvars(val:string|regexp|object=void):array|object Return details or list of matching variables. Returns all values, data or function.
versionversion(boolStr:string|boolean=false):number|string|object Return JSI version double, string or object when boolStr==true.

Options for "Info.cmds"

Option Type DescriptionFlags
fullBOOLReturn full path.
constructorBOOLDo not exclude constructor.

Return to top


Interp

Synopsis:new Interp(options:object=void):userobj

Commands for accessing interps.

Methods for "Interp"

MethodPrototypeDescription
Interpnew Interp(options:object=void):userobj Create a new interp.
aliasalias(name:string=void, func:function|null=void, args:array|null=void) 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, returns args for given alias name (args must be null). With 3 args, create/update an alias for func and args. Delete an alias by creating it with null for both func and args.
callcall(funcName:string, args:string|array, async: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 of true is given, we wait until the sub-interp is idle, make the call, and return the result. Otherwise the call is acyncronous.
confconf(options:string|object=void) Configure option(s).
evaleval(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.
infoinfo():object Returns internal statistics about interp.
sendsend(msg:any) Enqueue message onto a sub-interps recvCallback handler. Add messages to queue to be processed by the 'recvCallback' interp option.
sourcesource(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.
upleveluplevel(js:string, level:number=0) Interpret code at the given stack level: see Info.level(). The level argument is as returned by Info.level(). Not supported with threads.
valuevalue(var:string, level:number=0) Lookup value of variable at stack level: see Info.level().

Options for "new Interp"

Option Type DescriptionFlags
argsARRAYThe console.arguments for interp.initOnly
assertsBOOLEnable assert.
assertModeSTRKEYAction upon assert failure. (one of: throw, log, puts)
autoFilesVALUEFile(s) to source for loading Jsi_Auto to handle unknown commands.
busyCallbackSTRKEYCommand in parent interp (or 'event') to periodically call. Call func(interpName:string, opCnt:number).
busyIntervalINTCall busyCallback command after this many op-code evals (100000).initOnly
compatBOOLIgnore unknown options via JSI_OPTS_IGNORE_EXTRA in option parser.
coverageBOOLOn exit generate detailed code coverage for function calls (with profile).
debugOptsoptionsOptions for debugging.
historyFileSTRKEYIn interactive mode, file to use for history (~/.jsish_history).initOnly
isSafeBOOLIs this a safe interp (ie. with limited or no file access).initOnly
isttyBOOLIndicates interp is in interactive mode.readOnly
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).
logOptsoptionsOptions for log output to add file/line/time.
maxDepthINTDepth limit of recursive function calls (1000).
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.
msgAllowDupsBOOLDisable log duplicate filtering.
mutexUnlockBOOLUnlock own mutex when evaling in other interps (true).initOnly
nameSTRKEYOptional text name for this interp.
noInheritBOOLDisable OOP features such as __proto__, prototype, constructor, etc.
noReadlineBOOLDisable use of readline in interactive mode.
noUndefBOOLSuppress printing undefined value result when in interactive mode.
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
opTraceINTSet debugging level for OPCODE execution.
noSubInterpsBOOLDisallow sub-interp creation.initOnly
noStderrBOOLMake puts, log, assert, etc use stdout.
pkgDirsARRAYlist of library directories for require() to search.
profileBOOLOn exit generate profile of function calls.
noInheritBOOLDisable access to __proto__, prototype, constructor, etc.
recvCallbackSTRKEYCommand to recv 'send' msgs from parent interp. Call func(msg:string).
safeReadDirsARRAYIn safe mode, files/directories to allow reads from.initOnly
safeWriteDirsARRAYIn safe mode, files/directories to allow writes to.initOnly
safeExecPatternSTRKEYIn safe mode, regexp pattern allow exec of commands.initOnly
scriptStrSTRKEYInterp init script string.initOnly
scriptFileSTRINGInterp init script file.
showColumnsBOOLDisplay column numbers in error messages.
stdinStrSTRINGString to use as stdin for console.input().
stdoutStrSTRINGString to collect stdout for puts().
strictBOOLGlobally enable strict: same as 'use strict' in main program.
subthreadBOOLCreate a threaded Interp.initOnly
traceCallARRAYTrace commands. (zero or more of: funcs, cmds, new, return, args, notrunc, noparent, full, before)
tracePutsBOOLTrace puts by making it use logOpts.
typeCheckARRAYType-check control options. (zero or more of: parse, run, all, error, strict, noundef, nowith, proto)
typeWarnMaxINTType checking is silently disabled after this many warnings (50).
unitTestUINTUnit test control bits: 1=subst ;;, 2=Puts with file:line prefix.

Options for "debugOpts"

Option Type DescriptionFlags
callbackSTRKEYCommand in parent interp for handling debugging. Call func(file:string, line:number, level:number, func:string, opstr:string, bpId:number, emsg:string).
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.
msgCallbackSTRKEYComand in parent interp to handle log msgs. Call func(msg:string, type:string, file:string, line:number, col:number).
pkgTraceBOOLTrace package loads.
putsCallbackSTRKEYComand in parent interp to handle puts output. Call func(msg:string, isStderr:number).
traceCallbackSTRKEYComand in parent interp to handle traceCall. Call func(cmd:string, args:string, ret:string, file:string, line:number, col:number).

Options for "logOpts"

Option Type DescriptionFlags
TestBOOLEnable LogTest messages.
DebugBOOLEnable LogDebug messages.
TraceBOOLEnable LogTrace messages.
timeBOOLPrefix with time.
dateBOOLPrefix with date.
fileBOOLOuptut contains file:line.
funcBOOLOutput function.
fullBOOLShow full file path.
beforeBOOLOutput file:line before message string.
isUTCBOOLTime is to be UTC.
timeFmtSTRKEYA format string to use with strftime.
chanUSEROBJChannel to send output to.

Return to top


JSON

Synopsis:JSON.method(...)

Commands for handling JSON data.

Methods for "JSON"

MethodPrototypeDescription
checkcheck(str:string, strict:boolean=true):boolean Return true if str is JSON.
parseparse(str:string, strict:boolean=true) Parse JSON and return js.
stringifystringify(value:any, strict:boolean=true):string Return JSON from a js object.

Return to top


Math

Synopsis:Math.method(...)

Commands performing math operations on numbers.

Methods for "Math"

MethodPrototypeDescription
absabs(num:number):number Returns the absolute value of x.
acosacos(num:number):number Returns the arccosine of x, in radians.
asinasin(num:number):number Returns the arcsine of x, in radians.
atanatan(num:number):number Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians.
atan2atan2(x:number, y:number):number Returns the arctangent of the quotient of its arguments.
ceilceil(num:number):number Returns x, rounded upwards to the nearest integer.
coscos(num:number):number Returns the cosine of x (x is in radians).
expexp(num:number):number Returns the value of Ex.
floorfloor(num:number):number Returns x, rounded downwards to the nearest integer.
loglog(num:number):number Returns the natural logarithm (base E) of x.
maxmax(x:number, y:number, ...):number Returns the number with the highest value.
minmin(x:number, y:number, ...):number Returns the number with the lowest value.
powpow(x:number, y:number):number Returns the value of x to the power of y.
randomrandom():number Returns a random number between 0 and 1.
roundround(num:number):number Rounds x to the nearest integer.
sinsin(num:number):number Returns the sine of x (x is in radians).
sqrtsqrt(num:number):number Returns the square root of x.
tantan(num:number):number Returns the tangent of an angle.

Return to top


MySql

Synopsis:new MySql(options:object=void):userobj

Commands for accessing mysql databases.

Methods for "MySql"

MethodPrototypeDescription
MySqlnew MySql(options:object=void):userobj Create a new db connection to a MySql database:.
affectedRowsaffectedRows():number Return affected rows.
completecomplete(sql:string):boolean Return true if sql is complete.
confconf(options:string|object=void) Configure options.
errorNoerrorNo():number Return error code returned by most recent call to mysql3_exec().
errorStateerrorState():string Return the mysql error state str.
evaleval(sql:string):number Run sql commands without input/output.
existsexists(sql:string):boolean Execute sql, and return true if there is at least one result value.
infoinfo():object Return info about last query.
lastQuerylastQuery():string Return info string about most recently executed statement.
lastRowidlastRowid():number Return rowid of last insert.
onecolumnonecolumn(sql:string) Execute sql, and return a single value.
pingping(noError:boolean=false):number Ping connection.
queryquery(sql:string, options:function|object=void) Run sql query with input and/or outputs..
reconnectreconnect():void Reconnect with current settings.
resetreset():number Reset connection.

Options for "new MySql"

Option Type DescriptionFlags
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.
userSTRKEYDatabase user name. Default is current user-name..initOnly
versionDOUBLEMysql version number.readOnly

Options for "queryOpts"

Option Type DescriptionFlags
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)
nocacheBOOLQuery is not to be cached.
noNamedParamsBOOLDisable translating sql to support named params.
nullvalueSTRKEYNull string output (for non-json mode).
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.
varNameSTRKEYString name of array var for ? bind parameters.
widthCUSTOMIn column mode, set column widths.

Options for "MySql.query"

Option Type DescriptionFlags
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)
nocacheBOOLQuery is not to be cached.
noNamedParamsBOOLDisable translating sql to support named params.
nullvalueSTRKEYNull string output (for non-json mode).
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.
varNameSTRKEYString name of array var for ? bind parameters.
widthCUSTOMIn column mode, set column widths.

Return to top


Number

Synopsis:new Number(num:string=0):number

Commands for accessing number objects.

Methods for "Number"

MethodPrototypeDescription
Numbernew Number(num:string=0):number Number constructor.
isFiniteisFinite():boolean Return true if is finite.
isIntegerisInteger():boolean Return true if is an integer.
isNaNisNaN():boolean Return true if is NaN.
isSafeIntegerisSafeInteger():boolean Return true if is a safe integer.
toExponentialtoExponential(num:number):string Converts a number into an exponential notation.
toFixedtoFixed(num:number=0):string Formats a number with x numbers of digits after the decimal point.
toPrecisiontoPrecision(num:number):string Formats a number to x length.
toStringtoString(radix:number=10):string Convert to string.

Return to top


Object

Synopsis:new Object(val:object|null=void):object

Commands for accessing Objects.

Methods for "Object"

MethodPrototypeDescription
Objectnew Object(val:object|null=void):object Object constructor.
createcreate(proto:null|object, properties:object=void):object Create a new object with prototype object and properties.
getPrototypeOfgetPrototypeOf(name:object):object Return prototype of an object.
hasOwnPropertyhasOwnProperty(name:string):boolean Returns a true if object has the specified property.
isis(value1, value2):boolean Tests if two values are equal.
isPrototypeOfisPrototypeOf(name):boolean Tests for an object in another object's prototype chain.
keyskeys(obj:object=void):array Return the keys of an object or array.
propertyIsEnumerablepropertyIsEnumerable(name):boolean Determine if a property is enumerable.
setPrototypeOfsetPrototypeOf(name:object, value:object) Set prototype of an object.
toLocaleStringtoLocaleString(quote:boolean=false):string Convert to string.
toStringtoString(quote:boolean=false):string Convert to string.
valueOfvalueOf() Returns primitive value.

Return to top


RegExp

Synopsis:new RegExp(val:regexp|string):regexp

Commands for managing reqular expression objects.

Methods for "RegExp"

MethodPrototypeDescription
RegExpnew RegExp(val:regexp|string):regexp Create a regexp object.
execexec(val:string):array|object|null return matching string. Perform regexp match checking. Returns the array of matches.With the global flag g, sets lastIndex and returns next match.
testtest(val:string):boolean test if a string matches.

Return to top


Signal

Synopsis:Signal.method(...)

Commands for handling unix signals.

Methods for "Signal"

MethodPrototypeDescription
alarmalarm(secs):number Setup alarm in seconds.
callbackcallback(func:function, sig:number|string):number Setup callback handler for signal.
handlehandle(sig:number|string=void, ...) Set named signals to handle action.
ignoreignore(sig:number|string=void, ...) Set named signals to ignore action.
killkill(pid:number, sig:number|string='SIGTERM'):void Send signal to process id.
namesnames():array Return names of all signals.
resetreset(sig:number|string=void, ...):array Set named signals to default action.

Return to top


Socket

Synopsis:new Socket(options:object=void):userobj

Commands for managing Socket server/client connections.

Methods for "Socket"

MethodPrototypeDescription
Socketnew Socket(options:object=void):userobj Create socket server/client object.Create a socket server or client object.
closeclose():void Close socket(s).
confconf(options:string|object=void) Configure options.
idconfidconf(id:number=void, options:string|object=void) Configure options for a connection id, or return list of ids.
namesnames():array Return list of active ids on server.
recvrecv(id:number=void):string Recieve data.
sendsend(id:number, data:string, options:object=void):void Send a socket message to id. Send a message to a (or all if -1) connection.
updateupdate():void Service events for just this socket.

Options for "new Socket"

Option Type DescriptionFlags
addressVALUEClient destination address (127.0.0.0).initOnly
broadcastBOOLEnable broadcast.initOnly
connectCntINTCounter for number of active connections.readOnly
debugINTDebugging level.
interfaceVALUEInterface for server to listen on, eg. 'eth0' or 'lo'.initOnly
keepaliveBOOLEnable keepalive.initOnly
maxConnectsINTIn server mode, max number of client connections accepted.
mcastAddMemberVALUEMulticast add membership: address/interface ('127.0.0.1/0.0.0.0').initOnly
mcastInterfaceVALUEMulticast 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(id:number)
onCloseLastFUNCFunction to call when last connection closes. @function()
onOpenFUNCFunction to call when connection opens. @function(info:object)
onRecvFUNCFunction to call with recieved data. @function(id:number, data:string)
portINTPort for client dest or server listen (9000).initOnly
recvTimeoutUINT64Timeout for receive, in microseconds.initOnly
sendTimeoutUINT64Timeout for send, in microseconds.initOnly
serverBOOLEnable server mode.initOnly
srcAddressVALUEClient source address.initOnly
srcPortINTClient source port.initOnly
startTimeTIME_TTime of start.readOnly
tosINT8Type of service value.initOnly
ttlINTTime to live value.initOnly
createLastTIME_TTime of last create.readOnly
udpBOOLProtocol is udp.initOnly

Options for "Socket.idconf"

Option Type DescriptionFlags
recvCntINTNumber of recieves.
recvLastTIME_TTime of last recv.
sentCntINTNumber of sends.
sentLastTIME_TTime of last send.
sentErrCntINTNumber of sends.
sentErrLastTIME_TTime of last sendErr.
recvAddrCUSTOMIncoming port and address.

Options for "Socket.send"

Option Type DescriptionFlags
noAsyncBOOLSend is not async.

Return to top


Sqlite

Synopsis:new Sqlite(file:string=void, options:object=void):userobj

Commands for accessing sqlite databases.

Methods for "Sqlite"

MethodPrototypeDescription
Sqlitenew Sqlite(file:string=void, options:object=void):userobj Create a new db connection to the named file or :memory:.
authorizorauthorizor(callback:function=void):function Setup authorizor. db.authorizer(FUNC) Invoke the given callback to authorize each SQL operation as it is compiled. 5 arguments are appended to the callback before it is invoked: (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...) (2) First descriptive name (depends on authorization type) (3) Second descriptive name (4) Name of the database (ex: 'main', 'temp') (5) Name of trigger that is doing the access The callback should return on of the following strings: SQLITE_OK, SQLITE_IGNORE, or SQLITEN_DENY. Any other return value is an error. If this method is invoked with no arguments, the current authorization callback string is returned.
backupbackup(file:string, dbname:string='main'):void Backup db to file. db.backup(FILENAME, ?DATABASE?) Open or create a database file named FILENAME. Transfer the content of local database DATABASE (default: 'main') into the FILENAME database.
busybusy(callback:function=void):function Function callback upon open busy. Invoke the given callback when an SQL statement attempts to open a locked database file. Call with null to disable, or no arguments, to return the current busy function.
changeschanges():null Return the number of rows that were modified, inserted, or deleted by last command.
closeclose():void Close db.
collatecollate(name:string, callback:function):void Create new SQL collation command.
collation_neededcollation_needed(callback:null|function=void):function Set/get func to call on unknown collation.
commit_hookcommit_hook(callback:null|function=void):function Set/get func to call on commit. Invoke the given callback just before committing every SQL transaction. If the callback throws an exception or returns non-zero, then the transaction is aborted. If CALLBACK is an empty string, the callback is disabled.
completecomplete(sql:string):boolean Return true if sql is complete.
confconf(options:string|object=void) Configure options.
enable_load_extensionenable_load_extension(enable:boolean) En/disable loading of extensions (default false).
errorcodeerrorcode():null Return the numeric error code that was returned by the most recent call to sqlite3_exec().
evaleval(sql:string):void Run sql commands without input/output. Supports multiple semicolon seperated commands. Variable binding is NOT performed, results are discarded, and no value is returned
existsexists(sql:string):boolean Execute sql, and return true if there is at least one result value.
filenamefilename(name:string='main'):string Return filename for named or all attached databases.
funcfunc(name:string, callback:function, numArgs:number=void):void Register a new function with database.
importimport(table:string, file:string, options:object=void):number Import 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 'db.changes' due to the conflict algorithm selected.
interruptinterrupt():void Interrupt in progress statement.
lastInsertlastInsert():number Return rowid of last insert.
onecolumnonecolumn(sql:string) Execute sql, and return a single value.
profileprofile(callback:null|function=void):function Set/get func to call on every SQL executed. Call args are: SQL,time. Make arrangements to invoke the CALLBACK routine after each SQL statement that has run. The text of the SQL and the amount of elapse time are arguments to CALLBACK.
progressprogress(nth:number=void, callback:null|function=void):function Set/get func to call on every N VM opcodes executed.
queryquery(sql:string, options:function|object=void) Evaluate an sql query with bindings. Return values in formatted as JSON, HTML, etc. , optionally calling function with a result object
rekeyrekey(key:string):boolean Change the encryption key on the currently open database.
restorerestore(file:string, dbname:string):void Restore 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').
rollback_hookrollback_hook(callback:null|function=void):function Set/get func to call on rollback.
timeouttimeout(millisecs:number) Delay for the number of milliseconds specified when a file is locked.
total_changestotal_changes():number Return the number of rows that were modified, inserted, or deleted since db opened.
tracetrace(callback:null|function=void):function Set/get func to trace SQL: Call args are: SQL. Make arrangements to invoke the callback routine for each SQL statementthat is executed. The text of the SQL is an argument to callback.
transactiontransaction(callback:function, type:string=void):void Call function inside db tranasaction. Type is: 'deferred', 'exclusive', 'immediate'. db.transaction(FUNC ?,'deferred'|'immediate'|'exclusive'?) 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.
unlock_notifyunlock_notify(callback:null|function=void):function Set/get func to call on unlock.
update_hookupdate_hook(callback:null|function=void):function Set/get func to call on update: Call args are: OP,db,table,rowid.
versionversion():string Return database verion string.
wal_hookwal_hook(callback:null|function=void):function Set/get func to call on wal commit: Call args are: db,numEntries.

Options for "new Sqlite"

Option Type DescriptionFlags
bindWarnBOOLTreat failed variable binds as a warning.initOnly
debugARRAYEnable debug trace for various operations. (zero or more of: eval, delete, prepare, step)
errorCntINTCount of errors.readOnly
queryOptsoptionsDefault options for exec.
forceIntBOOLBind float as int if possible.
maxStmtsINTMax cache size for compiled statements.
mutexSTRKEYMutex type to use. (one of: default, none, full)initOnly
nameDSTRINGName for this db handle.
nocreateBOOLDatabase is must already exist (false).initOnly
numSortINTNumber of sorts in most recent operation.readOnly
numStepINTNumber of steps in most recent operation.readOnly
numStmtsINTCurrent size of compiled statement cache.readOnly
readonlyBOOLDatabase is readonly.initOnly
versionINTVersion number compiled against.readOnly
vfsVALUEVFS to use.initOnly

Options for "queryOpts"

Option Type DescriptionFlags
callbackFUNCFunction to call with each row result. @function(values:object)
cdataSTRKEYName of Cdata array object to use.
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)
nocacheBOOLQuery is not to be cached.
nullvalueSTRKEYNull string output (for non js/json mode).
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.
varNameSTRKEYArray var for ? bind parameters.
widthCUSTOMIn column mode, set column widths.

Options for "Sqlite.import"

Option Type DescriptionFlags
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.

Options for "Sqlite.query"

Option Type DescriptionFlags
callbackFUNCFunction to call with each row result. @function(values:object)
cdataSTRKEYName of Cdata array object to use.
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)
nocacheBOOLQuery is not to be cached.
nullvalueSTRKEYNull string output (for non js/json mode).
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.
varNameSTRKEYArray var for ? bind parameters.
widthCUSTOMIn column mode, set column widths.

Return to top


String

Synopsis:new String(str):string

Commands for accessing string objects..

Methods for "String"

MethodPrototypeDescription
Stringnew String(str):string String constructor.
charAtcharAt(index:number):string Return char at index.
charCodeAtcharCodeAt(index:number):number Return char code at index.
concatconcat(str:string, ...):string Append one or more strings.
indexOfindexOf(str:string, start:number):number Return index of char.
lastIndexOflastIndexOf(str:string, start:number):number Return index of last char.
mapmap(strMap:array, nocase:boolean=false):string Replaces characters in string based on the key-value pairs in strMap.
matchmatch(pattern:regexp|string):array|null Return array of matches.
replacereplace(pattern:regexp|string, replace:string|function):string Regex/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.Otherwise if the first argument is a regexp, the replace can contain the $ escapes: $&, $1, etc.
searchsearch(pattern:regexp|string):number Return index of first char matching pattern.
sliceslice(start:number, end:number):string Return section of string.
splitsplit(char:string|null=void):array Split on char and return Array: null removes empty elements.
substrsubstr(start:number, length:number):string Return substring.
substringsubstring(start:number, end:number):string Return substring.
toLocaleLowerCasetoLocaleLowerCase():string Lower case.
toLocaleUpperCasetoLocaleUpperCase():string Upper case.
toLowerCasetoLowerCase():string Return lower cased string.
toTitletoTitle(chars:string):string Make first char upper case.
toUpperCasetoUpperCase():string Return upper cased string.
trimtrim(chars:string):string Trim chars.
trimLefttrimLeft(chars:string):string Trim chars from left.
trimRighttrimRight(chars:string):string Trim chars from right.

Return to top


System

Synopsis:System.method(...)

Builtin system commands. All are callable from the either the top level or as System.XXX().

Methods for "System"

MethodPrototypeDescription
assertassert(expr:boolean|number|function, msg:string=void, options:object=void):void Throw or output msg if expr is false. Assert does nothing by default, but can be enabled with "use asserts" or setting Interp.asserts.
clearIntervalclearInterval(id:number):void Delete event id returned from setInterval/setTimeout/info.events().
decodeURIdecodeURI(val:string):string Decode an HTTP URL.
encodeURIencodeURI(val:string):string Encode an HTTP URL.
execexec(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
exitexit(code:number=0):void Exit the current interpreter.
formatformat(format:string, ...):string Printf style formatting: adds %q and %S.
isFiniteisFinite(val):boolean Return true if is a finite number.
isMainisMain():boolean Return true if current script was the main script invoked from command-line.
isNaNisNaN(val):boolean Return true if not a number.
loadload(shlib:string):void Load a shared executable and invoke its _Init call.
loglog(val, ...):void Same as puts, but includes file:line.
noOpnoOp() A No-Op. A zero overhead command call that is useful for debugging.
parseFloatparseFloat(val):number Convert string to a double.
parseIntparseInt(val:any, base:number=10):number Convert string to an integer.
parseOptsparseOpts(self:object, options:object, conf:object|null|undefined) Parse options.
printfprintf(format:string, ...):void Formatted output to stdout. Each argument is quoted. Use Interp.logOpts to control source line and/or timestamps output.
provideprovide(name:string=void, version:number=1):void Provide a package for use with require. Default is the file tail-rootname.
putsputs(val, ...):void Output one or more values to stdout. Each argument is quoted. Use Interp.logOpts to control source line and/or timestamps output.
quotequote(val:string):string Return quoted string.
requirerequire(name:string=void, version:number=1):number|array|object Load/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, also returns an object containing the version and loadFile, but if version argument is less than package version throws an error.
runModulerunModule(cmd:string|function=void, conf:array=undefined) Invoke named module. If name is empty, uses file basename. If isMain and no args givine parses console.args.
setIntervalsetInterval(callback:function, ms:number):number Setup recurring function to run every given millisecs.
setTimeoutsetTimeout(callback:function, ms:number):number Setup function to run after given millisecs.
sleepsleep(secs:number=1.0):void sleep for N milliseconds, minimum .001.
sourcesource(val:string|array, options:object=void):void Load and evaluate source files.
strftimestrftime(num:number=null, options:string|object=void):string Format numeric time (in ms) to a string. Null or no value will use current time.
strptimestrptime(val:string=void, options:string|object=void):number Parse time from string and return ms time since 1970-01-01 in UTC.
unloadunload(shlib:string):void Unload a shared executable and invoke its _Done call.
updateupdate(options:number|object=void):number Service 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.

Options for "System.assert"

Option Type DescriptionFlags
modeSTRKEYAction when assertion is false. Default from Interp.assertMode. (one of: throw, log, puts)
noStderrBOOLLogged msg to stdout. Default from Interp.noStderr.

Options for "System.exec"

Option Type DescriptionFlags
bgBOOLRun command in background using system() and return OS code.
inputStrSTRINGUse string as input and return OS code.
noErrorBOOLSuppress all OS errors.
noRedirBOOLDisable redirect and shell escapes in command.
noTrimBOOLDo not trim trailing whitespace from output.
retAllBOOLReturn the OS return code and data as an object.
retCodeBOOLReturn only the OS return code.

Options for "System.source"

Option Type DescriptionFlags
autoIndexBOOLLook for and load Jsi_Auto.jsi auto-index file.
isMainBOOLCoerce to true the value of Info.isMain().
onceBOOLSource file only if not already sourced (Default: Interp.debugOpts.includeOnce).
traceBOOLTrace include statements (Default: Interp.debugOpts.includeTrace).

Options for "System.strftime"

Option Type DescriptionFlags
secsBOOLTime is seconds (out for parse, in for format).
fmtSTRKEYFormat string for time.
utcBOOLTime is utc (in for parse, out for format).

Options for "System.strptime"

Option Type DescriptionFlags
secsBOOLTime is seconds (out for parse, in for format).
fmtSTRKEYFormat string for time.
utcBOOLTime is utc (in for parse, out for format).

Options for "System.update"

Option Type DescriptionFlags
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.

Return to top


Util

Synopsis:Util.method(...)

Utilities commands.

Methods for "Util"

MethodPrototypeDescription
base64base64(val:string, decode:boolean=false):string Base64 encode/decode a string.
crc32crc32(val:string, crcSeed=0):number Calculate 32-bit CRC.
decryptdecrypt(val:string, key:string):string Decrypt data using BTEA encryption. Keys that are not 16 bytes use the MD5 hash of the key.
encryptencrypt(val:string, key:string):string Encrypt data using BTEA encryption. Keys that are not 16 bytes use the MD5 hash of the key.
fromCharCodefromCharCode(code:number):string Return char with given character code.
getenvgetenv(name:string=void):string|object|void Get one or all environment.
getpidgetpid(parent:boolean=false):number Get process/parent id.
hashhash(val:string, options|object=void):string Return hash (default SHA256) of string/file.
hexStrhexStr(val:string, decode:boolean=false):string Hex encode/decode a string.
markdownmarkdown(val:string, options:object=void):string|object Render markdown.
setenvsetenv(name:string, value:string=void) Set/get an environment var.
timestimes(callback:function, count:number=1):number Call function count times and return execution time in microseconds.

Options for "Util.hash"

Option Type DescriptionFlags
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)

Options for "Util.markdown"

Option Type DescriptionFlags
topLinkSTRKEYWeb server root url.
returnStrBOOLReturn just HTML string instead of an object.
getTitleBOOLExtract title from first H1 in page.

Return to top


Vfs

Synopsis:Vfs.method(...)

Commands for creating in memory readonly Virtual file-systems.

Methods for "Vfs"

MethodPrototypeDescription
confconf(mount:string, string|options:object|string=void) Configure mount.
execexec(cmd:string) Safe mode exec for VFS support cmds eg. fossil info/ls/cat.
fileconffileconf(mount:string, path:string, options:string|object=void) Configure file info which is same info as in fileList.
listlist():array Return list of all vfs mounts.
mountmount(type:string, target:string, param:object=void):string Mount target as given VFS type name, returning the mount point.
typetype(type:string=void, options:object|null=void) Set/get/delete VFS type name.
unmountunmount(mount:string):void Unmount a VFS.
vmountvmount(options:object=void):string Create and mount a VFS, returning the mount point.

Options for "Vfs.conf"

Option Type DescriptionFlags
callbackFUNCFunction implementing VFS. @function(op:string, mount:string, arg:string|object|null)
extraOBJExtra info, typically used by predefined VFS type.
noAddDirsBOOLDisable auto-adding of directories; needed by File.glob.
fileListARRAYList of files in the VFS (from listFunc).
infoOBJInfo for VFS target stored upon init.
mountSTRINGMount point for the VFS.
paramOBJOptional 3rd argument passed to mount.
targetSTRINGTarget string.
typeSTRKEYType for predefined VFS.
userOBJUser data.

Options for "Vfs.exec"

Option Type DescriptionFlags
dataSTRINGData for file.
fileSTRKEYFile pathname.required
permsUINT32Permissions for file.
sizeSSIZE_TSize of file.
timestampTIME_TTimestamp of file.

Options for "Vfs.fileconf"

Option Type DescriptionFlags
dataSTRINGData for file.
fileSTRKEYFile pathname.required
permsUINT32Permissions for file.
sizeSSIZE_TSize of file.
timestampTIME_TTimestamp of file.

Options for "Vfs.type"

Option Type DescriptionFlags
callbackFUNCFunction implementing VFS. @function(op:string, mount:string, arg:string|object|null)required
extraOBJExtra info, typically used by predefined VFS type.
noAddDirsBOOLDisable auto-adding of directories; needed by File.glob.

Options for "Vfs.vmount"

Option Type DescriptionFlags
callbackFUNCFunction implementing VFS. @function(op:string, mount:string, arg:string|object|null)
extraOBJExtra info, typically used by predefined VFS type.
noAddDirsBOOLDisable auto-adding of directories; needed by File.glob.
fileListARRAYList of files in the VFS (from listFunc).
infoOBJInfo for VFS target stored upon init.
mountSTRINGMount point for the VFS.
paramOBJOptional 3rd argument passed to mount.
targetSTRINGTarget string.
typeSTRKEYType for predefined VFS.
userOBJUser data.

Return to top


WebSocket

Synopsis:new WebSocket(options:object=void):userobj

Commands for managing WebSocket server/client connections.

Methods for "WebSocket"

MethodPrototypeDescription
WebSocketnew WebSocket(options:object=void):userobj Create 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.
confconf(options:string|object=void) Configure options.
handlerhandler(extension:string=void, cmd:string|function=void, arg:string|null=void, flags:number=0):string|array|function|undefined Get/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 runModule([cmd], arg).If a cmd is a function, it is called with a single arg: the file name.
headerheader(id:number, name:string=void):string|object|undefined Get one or all headers for connect id.
idconfidconf(id:number, options:string|object=void) Configure options for connect id.
idsids():array Return list of ids.
sendsend(id:number, data:any):void Send 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.
updateupdate():void Service events for just this websocket.
versionversion():string Runtime library version string.

Options for "new WebSocket"

Option Type DescriptionFlags
addressSTRINGIn client-mode the address to connect to (127.0.0.1).
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 libwebsocket log levels.
defaultUrlSTRINGDefault when no url or / is given.
extArgsOBJArguments for extension handlers.initOnly
extHandlersBOOLEnable builtin handlers for extensions: .htmli, .cssi, .jsi, and .md.initOnly
getRegexpREGEXPCall onGet() only if Url matches pattern.
interfaceSTRINGInterface for server to listen on, eg. 'eth0' or 'lo'.initOnly
localBOOLLimit connections to localhost addresses on the 127 network.
maxConnectsINTIn server mode, max number of client connections accepted.
mimeTypesOBJObject providing map of file extensions to mime types (eg. {txt:'text/plain', bb:'text/bb'}).initOnly
noUpdateBOOLDisable update event-processing (eg. to exit).
noWebsockBOOLServe html, but disallow websocket upgrade.initOnly
noWarnBOOLQuietly ignore file related errors.
onAuthFUNCFunction to call for http basic authentication. @function(id:number, url:string, userpass:string)
onCloseFUNCFunction to call when the websocket connection closes. @function(id:number)
onCloseLastFUNCFunction to call when last websock connection closes. @function()
onFilterFUNCFunction to call on a new connection: return false to kill connection. @function(id:number, urlprot:string, ishttp:boolean)
onGetFUNCFunction to call to server handle http-get. @function(id:number, url:string, args:object)
onOpenFUNCFunction to call when the websocket connection occurs. @function(id:number)
onUnknownFUNCFunction to call to server out content when no file exists. @function(id:number, url:string, args:object)
onUploadFUNCFunction to call handle http-post: called when upload starts and completes. @function(id:number, complete:boolean)
onRecvFUNCFunction to call when websock data recieved. @function(id:number, data:string)
maxDownloadINTMax size of file download.
maxUploadINTMax size of file upload will accept.
portINTPort for server to listen on (8080).initOnly
protocolSTRKEYName of protocol (ws/wss).
recvBufSizeINTLarge recv buffer size, eg. to ensure full JSON was been received. -1=disable, 0=default of 1024.initOnly
recvBufTimeoutINTTimeout wait for recv to finish. 0=default of 60 seconds.initOnly
redirectUrlSTRINGRedirect to, when no url or / is given.
redirDisableBOOLDisable redirects.
rootdirVALUEDirectory to serve html from (".").
statsoptionsStatistical data.readOnly
startTimeTIME_TTime of websocket start.readOnly
use_sslBOOLUse https (for client).initOnly
useridPassSTRKEYThe USER:PASSWD to use for basic authentication.
versionINTVersion number compiled against.readOnly

Options for "WebSocket.idconf"

Option Type DescriptionFlags
clientIPSTRKEYClient IP Address.readOnly
clientNameSTRKEYClient hostname.readOnly
onCloseFUNCFunction to call when the websocket connection closes. @function(id:number)
onGetFUNCFunction to call to server handle http-get. @function(id:number, url:string, args:object)
onUnknownFUNCFunction to call to server out content when no file exists. @function(id:number, url:string, args:object)
onRecvFUNCFunction to call when websock data recieved. @function(id:number, data:string)
onUploadFUNCFunction to call handle http-post: called when upload starts and completes. @function(id:number, complete:boolean)
rootdirVALUEDirectory to serve html from (".").
statsoptionsStatistics for connection.readOnly
isWebsockBOOLSocket has been upgraded to a websocket connection.
uploadDataDSTRINGUploaded data (raw).

Options for "stats"

Option Type DescriptionFlags
connectCntINTNumber of active connections.readOnly
httpCntINTNumber of http reqs.readOnly
httpLastTIME_TTime of last http reqs.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

Return to top


Zvfs

Synopsis:Zvfs.method(...)

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

Methods for "Zvfs"

MethodPrototypeDescription
appendappend(archive:string, filelist:array, path:string|null=void, filelist:array=void, path:string|null=void, ...):void Like 'create()', but appends to an existing archive (with no dup checking).
createcreate(archive:string, filelist:array, path:string|null=void, filelist:array=void, path:string|null=void, ...):void Create 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');
listlist(archive:string):array List 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' ]
mountmount(archive:string, mountdir:string=void):string Mount zip on mount point. Read a ZIP archive and make entries in the virutal file hash table for all files contained therein.
namesnames(mountdir:string=void):array Return 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
offsetoffset(archive:string):number Return 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.
statstat(filename:string):object Return 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.
truncatetruncate(archive:string, noerror:boolean=false):number Truncate 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.
unmountunmount(archive:string):void Unmount zip.

Return to top


console

Synopsis:console.method(...)

Console input and output.

Methods for "console"

MethodPrototypeDescription
assertassert(expr:boolean|number|function, msg:string=void, options:object=void):void Same as System.assert().
inputinput():string|void Read input from the console.
loglog(val, ...):void Same as puts, but goes to stderr and includes file:line.
logflogf(format:string, ...):void Same as printf, but goes to stderr and includes file:line and newline. Also, if there are multiple arguments, and the first argument does not contains a %, the second argument is the format, and the first is prepended to the output. This command is used with bind/alias to handle LogDebug, LogTrace, ...
putsputs(val, ...):void Output one or more values to stderr. Each argument is quoted. Use Interp.logOpts to control source line and/or timestamps output.

Options for "console.assert"

Option Type DescriptionFlags
modeSTRKEYAction when assertion is false. Default from Interp.assertMode. (one of: throw, log, puts)
noStderrBOOLLogged msg to stdout. Default from Interp.noStderr.

Return to top

(page auto-generated)