jsish
Reference
Not logged in

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

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


Array

Synopsis:new Array(...):array

Provide access to array objects.

Methods

The following methods are available in "Array":
MethodPrototypeDescription
Arraynew Array(...):array Array constructor.
concatconcat(...):array Return array with args appended.
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.
forEachforEach(callback:function, this:object=void):array Invoke function with each item in array.
indexOfindexOf(str:any, startIdx:number=0):number Return index of first occurrance in 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 on first element function returns true on.
sortsort(compare:function=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.

Return to top


Boolean

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

A Boolean object.

Methods

The following methods are available in "Boolean":
MethodPrototypeDescription
Booleannew Boolean(bool:boolean=false):boolean Boolean constructor.

Return to top


CData

Synopsis:CData.method(...)

Access commands for CData.

Methods

The following methods are available in "CData":
MethodPrototypeDescription
getget(name:string, index:number, field:string=void) Return struct data for one or all fields.
infoinfo(name:string):object Return struct details.
namesnames():array Return name of all defined CData items.
schemaschema(name:string):string Return a DB schema compatible with struct.
schemaMd5schemaMd5(name:string):string Calculate md5 of schema (ignores comments from .help).
setset(name:string, index:number, dataobj:string|object|null,) Update/get struct data.
sizesize(name:string):number Return allocated size of data array.
structstruct(name:string):string Return the C struct for mydata.

Return to top


Channel

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

Commands for accessing Channel objects for file IO.

Methods

The following methods are available in "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():void 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 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 Read some or all of file.
seekseek(pos:number, whence:number):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

The following methods are available in "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

The following methods are available in "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"

The following options are available 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

The following methods are available in "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:string|boolean|object=void):array Return list of files in dir with optional pattern match. With no arguments (or null) returns all files/directories in current directory. If first argument is a pattern (either a glob or regexp) just files are returned. If second argument is a string, it denotes the directory to search in. If second argument is a function, this function is called with each path. Otherwise second arugment is 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):null 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"

The following options are available for "File.glob"
Option Type DescriptionFlags
dirVALUEDirectory.
maxDepthINTMax depth to recurse to.
dirfuncFUNCReturns true to recurse into dir.
funcFUNCFunction that returns true to keep.
maxINTMax results to return.
notypesVALUEFile types to exclude, one or more of chars 'fdlpsbc' for file, directory, link, etc.
prefixSTRKEYString prefix to add to each file in list.
recurseBOOLRecurse into directories.
tailsBOOLReturn only the tails.
typesVALUEFile types to include, one or more of chars 'fdlpsbc' for file, directory, link, etc.

Return to top


Function

Synopsis:new Function():function

Commands for accessing functions.

Methods

The following methods are available in "Function":
MethodPrototypeDescription
Functionnew Function():function Function constructor (unimplemented).
applyapply(thisArg:null|object, args:array=void) Call function passing args array.
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

The following methods are available in "Info":
MethodPrototypeDescription
argv0argv0():string 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 for string.
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 If executing a .zip file, return file name.
executableexecutable():string Return name of executable.
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):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, a 0 translates to 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):string 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 Get current script file name, or file containing function.
scriptDirscriptDir():string 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(asObj:boolean=false):number|object Return JSI version double (or object when asObj==true).

Options for "Info.cmds"

The following options are available 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

The following methods are available in "Interp":
MethodPrototypeDescription
Interpnew Interp(options:object=void):userobj Create a new interp.The new interp may optionally be threaded.
aliasalias(name:string=void, func:function|null=void, args:array|function|null=void) Set/get alias command in the interp.
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"

The following options are available for "new Interp"
Option Type DescriptionFlags
isSafeBOOLInterp is safe (ie. limited or no file access).initOnly
debugOptsoptionsOptions for debugging.
argsARRAYThe console.arguments for interp.initOnly
autoFilesVALUEFile(s) to source for loading JsiAuto to handle unknown commands.
busyCallbackSTRKEYCommand in parent interp (or 'event') to periodically call. Call args: subinterp-name, op-cnt.initOnly
busyIntervalINTCall busyCallback command after this many op-code evals (100000).initOnly
callTraceINTTrace command calls and returns.
coverageBOOLOn exit generate detailed code coverage for function calls (with profile).
isttyBOOLIndicates interp is in interactive mode.readOnly
pkgDirsARRAYlist of library directories for require() to search.
lockTimeoutINTThread time-out for mutex lock acquires (milliseconds).
logCallbackSTRKEYComand in parent interp to handle log msgs. Called args: msg, type, file, line, col.initOnly
logAllowDupsBOOLDisable log duplicate filtering.
maxDepthINTRecursive call depth limit (1000).
maxIncDepthINTMaximum file include nest depth (50).
maxInterpDepthINTMaximum nested subinterp create depth (10).
maxUserObjsINTMaximum number of 'new' object calls, eg. File, RegExp, etc.
maxOpCntINTExecution limit for op-code evaluation.
memDebugINTMemory debugging level: 1=summary, 2=detail.
mutexUnlockBOOLUnlock own mutex when evaling in other interps (true).initOnly
nameSTRKEYOptional text name for this interp.
noAssertBOOLAssert statement disabled and treated as a no-op.
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.
onCompleteFUNCCommand that returns command-completion.
onEvalFUNCFunction to get control for interactive evals.
onExitFUNCCommand to call in parent on exit, which returns true to continue.initOnly
opTraceINTSet debugging level for OPCODE execution.
noSubInterpsBOOLDisallow sub-interp creation.initOnly
profileBOOLOn exit generate profile of function calls.
noInheritBOOLDisable access to __proto__, prototype, constructor, etc.
recvCallbackSTRKEYCommand to recv 'send' msgs from parent interp.
safeReadDirsARRAYIn safe mode, directories to allow reads from.initOnly
safeWriteDirsARRAYIn safe mode, directories to allow writes to.initOnly
scriptStrSTRKEYInterp init script string.initOnly
scriptFileVALUEInterp init script file.
showColumnsBOOLDisplay column numbers in error messages.
strictBOOLSame thing as 'use strict' in main program.
compatBOOLIgnore unknown options via JSI_OPTS_IGNORE_EXTRA in option parser.
subthreadBOOLCreate Interp with threads.initOnly
typeCheckARRAYType-check control options. (zero or more of: parse, run, proto, error)
typeWarnMaxINTType checking is silently disabled after this many warnings (50).

Options for "debugOpts"

The following options are available for "debugOpts"
Option Type DescriptionFlags
callbackSTRKEYString name of callback function in parent interp for handling debugging.initOnly
doContinueBOOLContinue execution until breakpoint.
forceBreakBOOLForce debugger to break.
minLevelINTDisable eval callback for level higher than this.
pkgTraceBOOLTrace package loads.

Return to top


JSON

Synopsis:JSON.method(...)

Commands for handling JSON data.

Methods

The following methods are available in "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

The following methods are available in "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

The following methods are available in "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"

The following options are available 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"

The following options are available for "queryOpts"
Option Type DescriptionFlags
callbackFUNCFunction to call with each row result.
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"

The following options are available for "MySql.query"
Option Type DescriptionFlags
callbackFUNCFunction to call with each row result.
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:number=0):number

Commands for accessing number objects.

Methods

The following methods are available in "Number":
MethodPrototypeDescription
Numbernew Number(num:number=0):number Number constructor.
toExponentialtoExponential(num:number):string Converts a number into an exponential notation.
toFixedtoFixed(num:number):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

The following methods are available in "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

The following methods are available in "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

The following methods are available in "Signal":
MethodPrototypeDescription
alarmalarm(secs):number Setup alarm in seconds.
callbackcallback(func:function, sig:number|string):number Setup callback handler for signal.
defaultdefault(sig:number|string=void, ...):array Set named signals to default action.
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.

Return to top


Socket

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

Commands for managing Socket server/client connections.

Methods

The following methods are available in "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(data:string, options:number|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"

The following options are available for "new Socket"
Option Type DescriptionFlags
addressVALUEClient destination address (127.0.0.0).initOnly
connectCntINTCounter for number of active connections.readOnly
debugINTDebugging level.
interfaceVALUEInterface for server to listen on, eg. 'eth0' or 'lo'.initOnly
maxConnectsINTIn server mode, max number of client connections accepted.
noAsyncBOOLSend is not async.initOnly
noUpdateBOOLStop processing update events (eg. to exit).
onCloseFUNCFunction to call when connection closes.
onCloseLastFUNCFunction to call when last connection closes.
onConnectFUNCFunction to call when connection starts.
onOpenFUNCFunction to call when connection opens.
onRecvFUNCFunction to call with recieved data.
portINTPort for client dest or server listen (9000).initOnly
serverBOOLEnable server mode.initOnly
startTimeTIMESTAMPTime of start.readOnly
createLastTIMESTAMPTime of last create.readOnly
udpBOOLProtocol is udp.initOnly

Options for "Socket.idconf"

The following options are available for "Socket.idconf"
Option Type DescriptionFlags
recvCntINTNumber of recieves.
recvLastTIMESTAMPTime of last recv.
sentCntINTNumber of sends.
sentLastTIMESTAMPTime of last send.
sentErrCntINTNumber of sends.
sentErrLastTIMESTAMPTime of last sendErr.
recvAddrCUSTOMIncoming port and address.

Options for "Socket.send"

The following options are available for "Socket.send"
Option Type DescriptionFlags
idINTId to send to, or -1 for all.
noAsyncBOOLSend is not async.

Return to top


Sqlite

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

Commands for accessing sqlite databases.

Methods

The following methods are available in "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"

The following options are available 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
vfsVALUEVFS to use.initOnly

Options for "queryOpts"

The following options are available for "queryOpts"
Option Type DescriptionFlags
callbackFUNCFunction to call with each row result.
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).
CDataSTRKEYName of CData object to use.
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"

The following options are available 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"

The following options are available for "Sqlite.query"
Option Type DescriptionFlags
callbackFUNCFunction to call with each row result.
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).
CDataSTRKEYName of CData object to use.
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

The following methods are available in "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.
fromCharCodefromCharCode(code:string, ...):string Return char its code number.
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 for each match with one parameter: the matching string. 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):array Split on char and return Array.
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

The following methods are available in "System":
MethodPrototypeDescription
assertassert(expr:boolean|number|function, msg:string) Throw error msg if expr evaluates to false/zero, and return arg 1.
b64decodeb64decode(val:string, isfile:boolean=false):string Decode string/file.
b64encodeb64encode(val:string, isfile:boolean=false):string Encode string/file.
clearIntervalclearInterval(id:number):void Delete event id returned from setInterval/setTimeout/info.events().
decodeURIdecodeURI(val:string):string Decode an HTTP URL.
decryptdecrypt(key:string, val:string):string Return decryption of string. Btea decrypt data using key string.
encodeURIencodeURI(val:string):string Encode an HTTP URL.
encryptencrypt(key,string, val:string):string Return encryption of string. Btea encryption data using key string. Input data is first padded with NULLs making the length a multiple of 4. If this is a problem, data can be b64encoded.
execexec(val:string, options:null|string|object=void) Execute an OS command. If the command ends with '&', set the 'bg' option to true. If the second argument is null, set the 'noError' option to true. If the second argument is a string, the 'inputStr' option is set. 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 Implement printf style formatting, plus %j JSON escapes.
getenvgetenv(name:string=void):string|object Get one or all environment.
getpidgetpid():number Get process id.
getppidgetppid():number Get parent process id.
isFiniteisFinite(val:string):boolean Return true if is a finite number.
isNaNisNaN(val:string):boolean Return true if not a number.
loadload(shlib:string):void Load a shared executable and invoke its _Init call.
md5md5(val:string, isfile:boolean=false):string Compute md5 hash of string/file.
noOpnoOp():void Do nothing; useful for measuring function call overhead.
parseFloatparseFloat(val):number Convert string to a double.
parseIntparseInt(val:any, base:number=10):number Convert string to an integer.
printfprintf(fmt, ...):void Formatted output to stdout. Each argument is quoted
provideprovide(name:string, version:number=1):void Provide a package for use with require.
putsputs(val, ...):void Output one or more values to stderr. Each argument is quoted
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.
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.
setenvsetenv(name:string, value:string) Set an environment var.
sha1sha1(val:string, isfile:boolean=false):string Return sha1 of string/file.
sha256sha256(val:string, isfile:boolean=false):string Return sha256 of string/file.
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, options:string|object=void):string Format numeric time (in ms) to a string. Giving null as the value will use current time.
strptimestrptime(val:string, options:string|object=void):number Parse time from string and return time (in ms) since 1970.
timestimes(callback:function, count:number=1):number Call function count times and return execution time in microseconds.
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.exec"

The following options are available 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.
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"

The following options are available for "System.source"
Option Type DescriptionFlags
debugINTDebugging level.
autoIndexBOOLLook for and load JsiAuto.jsi auto-index file.
isMainBOOLCoerce to true the value of Info.isMain().

Options for "System.strftime"

The following options are available for "System.strftime"
Option Type DescriptionFlags
utcBOOLtime is in utc.
fmtSTRKEYformat string for time.

Options for "System.strptime"

The following options are available for "System.strptime"
Option Type DescriptionFlags
utcBOOLtime is in utc.
fmtSTRKEYformat string for time.

Options for "System.update"

The following options are available 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


WebSocket

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

Commands for managing WebSocket server/client connections.

Methods

The following methods are available in "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):function 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. Call is via JsiMain(['arg2'], arg3).
idconfidconf(id:number, options:string|object=void) Configure options for id.
idsids():array Return list of ids.
sendsend(data:any, id:number=-1):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.

Options for "new WebSocket"

The following options are available for "new WebSocket"
Option Type DescriptionFlags
connectCntINTNumber of active connections.readOnly
addressVALUEAddress for client to connect to (127.0.0.1).
callbackFUNCFunction to callback when event occurs.
clientBOOLRun in client mode.initOnly
debugINTSet debug level.
defaultUrlVALUEDefault url to serve out (./).
interfaceVALUEInterface for server to listen on, eg. 'eth0' or 'lo'.initOnly
maxConnectsINTIn server mode, max number of client connections accepted.
mimeTypesVALUEMap of file extensions to mime types (eg. {txt:'text/plain', bb:'text/bb'}).initOnly
noUpdateBOOLStop processing update events (eg. to exit).
noWebsockBOOLServe html, but disallow websockets.initOnly
noWarnBOOLQuietly ignore file not found.
onCloseFUNCFunction to call when connection closes.
onCloseLastFUNCFunction to call when last connection closes.
onConnectFUNCFunction to call when connection starts (return false to kill).
onOpenFUNCFunction to call when connection opens.
portINTPort for server to listen on (8080).initOnly
rootdirVALUEDirectory to serve html from (./).
startTimeTIMESTAMPTime started.readOnly
use_sslBOOLUse https (for client).initOnly

Options for "WebSocket.idconf"

The following options are available for "WebSocket.idconf"
Option Type DescriptionFlags
httpCntINTNumber of http reqs.readOnly
httpLastTIMESTAMPTime of last http reqs.readOnly
recvCntINTNumber of recieves.readOnly
recvLastTIMESTAMPTime of last recv.readOnly
sentCntINTNumber of sends.readOnly
sentLastTIMESTAMPTime of last send.readOnly
sentErrCntINTNumber of sends.readOnly
sentErrLastTIMESTAMPTime of last sendErr.readOnly

Return to top


Zvfs

Synopsis:Zvfs.method(...)

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

Methods

The following methods are available in "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

The following methods are available in "console":
MethodPrototypeDescription
inputinput():string Read input from the console.
loglog(val, ...):void Output one or more values to stderr. Each argument is quoted

Return to top

(page auto-generated)