ActiveX

Properties

classNameString "ActiveX"
membersObject A hash table describing the functions and properties of the COM object. Use for (var x in obj.members) {writeln(x,'=',obj.members[x]);} to view the list and the COM-supplied documentation.

Functions

ActiveX( id String, forceNew Any)
id CLSID or object title from the registry
forceNew CLSID or object title from the registry
The constructor tries to connect the active object in a COM class. If there is no active object, it will try to create one with CoCreateInstance(). The constructor will throw an exception if the COM class does not implement the IDispatch interface. If you use a second parameter (of any value), a new COM object will always be created.
close( )
Closes the COM object and frees unused ActiveX libraries.
get( name String) returns Object
If a COM property ID is less than 255, it will appear as an automatic property of the JS object. Otherwise, use get() and set() to read and change property values. Recognized VARIANT types are BOOLEAN, INT4, DOUBLE, NULL, BSTR, IUnknown, and IDispatch.
set( name String, value Any) returns Object
If a COM property ID is less than 255, it will appear as an automatic property of the JS object. Otherwise, use get() and set() to read and change property values. The property must accept VARIANT types of BOOLEAN, INT4, DOUBLE, NULL, or BSTR.
toString( ) returns String
invokes the COM toString(...) method. If that function doesn't exist, it returns the property with index=0.
idl file:
  [propget, id(0), helpstring("property toString")] HRESULT toString([out,retval] VARIANT *rv);
implementation:
  STDMETHODIMP CFoo::get_whoami(VARIANT *rv)
  {
    rv->vt = VT_BSTR;
    rv->bstrVal = SysAllocString(L"[Foo object]");
    return S_OK;
  }

Archive

Properties

countNumber Number of files included in the archive.

Functions

Archive( file String|Stream)
The constructor needs a seekable stream (like a file or memory) or a filename. The stream used to open the archive will be kept open (even if it is deleted) until the archive is freed.
close( )
Closes the archive and frees the stream.
extract( index Number|String, stream Stream) returns Number
If the 2nd parameter is a stream, data are uncompressed to that stream. Otherwise, a new memory stream is returned containing the file data.
find( name String) returns Number
Returns the index of the file, or -1 if it does not exist
has( name String|Number) returns Number
Returns true if the file is in the archive
name( index Number) returns String
Returns the filename.
size( index Number) returns Number
Returns the uncompressed size of the file.

Form

Properties

countNumber number of questions
file_idNumber FORM tag index (usually zero)
nameString the filename of the EZF file
optionsRecord form options

Functions

Form( name String|Stream, index Number) returns Form
name Form filename, XML text, or a Stream.
index A HTML file may contain multiple
tags. If you don't want to load read the first of these, specify the form's index within the file.
Reads an EZF or HTML form into memory. This is a special-purpose XML interpreter. Question properties are accessed using the getXXX() and setXXX() functions. Question properties you can use are:
  • Name (fieldname): String
  • Text :String
  • Description:String
  • Length: Number
  • Help: String
  • Extra (unparsed XML within the question): String
  • Type: String (see below)
  • Responses: Record (names = codes, values = descriptions)
  • Options: Record
  • Skips: Record
For each of these properties, there is a getXXX() and setXXX() function, whose syntax are similar to getType() and setType(), described below.
addQuestion( Type String, Fieldname String, Text String, Description String, Responses String, Length Integer, Options String, Before Integer) returns Number
Responses Pipe-delimited list of codes and values
Options Pipe-delimited list of options
Before Insert before this question (-1 for end)
find( fieldname String) returns Number
fieldname Field name
Returns the question number (starting with 0) that matches a given fieldname.
getType( index Number) returns String
index Question number (starting with 0)
Retrieves a question type. Question types are:
Text
Password
Date
Time
Number
Radio
Weighted
Check
Single
Multiple
Combo
Rank
Hidden
Section
Page
RichText
Image
PlainText
ToolButton
hasData( index Number) returns Boolean
index Question number (starting with 0)
Returns true if the field can contain data, or false if it's a layout object.
isPageStart( index Number) returns Boolean
index Question number
Determines if the question starts a new page. This is the case if
  • the previous question has the "end-of-page" attribute (EZSurvey)
  • the question is a PAGE type (created in InterForm)
  • the question has the "new-page" attribute (EZSurvey)
  • the question is a Section type following a non-Section type question
  • the question is the first one in the form
move( start Number, finish Number) returns Boolean
start Question index
finish Question index
Moves a question from the start position to the finish position in the form. The other questions are rearranged, so you should be careful about using this while iterating over the questions.
remove( index Number) returns Boolean
index Question index
Deletes a question. The questions after index are moved up, so you should be careful about using this while iterating over the questions.
save( filename String) returns String
filename optional new file name
Saves changes.
setType( index Number, type String) returns String
index Question number (starting with 0)
type New value
Changes a question type. See getType() for the list of types.

Image

Properties

colorsNumber Number of colors (in addition to the background)
heightNumber Height
sizeNumber Number of bytes as a GIF file
widthNumber Width

Functions

Image( height Number, width Number) returns Image
height Height
width Width
Creates a new GIF image. The background color is white (color 0) and the transparent color is 127. There are 126 user-definable colors.
arc( X1 Number, Y1 Number, R Number, start Number, stop Number, color Number) returns Boolean
X1 start point
Y1 start point
R radius
start start angle (radians)
stop stop angle (radians)
color Color index
Draws an arc.
color( R Number, G Number, B Number) returns Integer
R 0..255
G 0..255
B 0..255
Adds a new color and returns its index.
fill( X1 Number, Y1 Number, color Number) returns Boolean
X1 start point
Y1 start point
color Color index
Fills all connected background-colored pixels with the new color.
getp( X1 Number, Y1 Number) returns Number
X1 x position
Y1 y position
Returns the pixel value at a point
line( X1 Number, Y1 Number, X2 Number, Y2 Number, color Number) returns Boolean
X1 start point
Y1 start point
X2 end point
Y2 end point
color Color index
Draws a 1-pixel line.
print( X Number, Y Number, color Number, text String, background Number) returns Boolean
X start point
Y start point
color Color index
text Text to display
background Background color index (default is 0)
Prints text. At present, the only font is 9-pixel sans-serif.
setBGColor( R Number, G Number, B Number) returns Boolean
R 0..255
G 0..255
B 0..255
Sets the background color value (color 0).
setp( X1 Number, Y1 Number, C Number) returns Boolean
X1 x position
Y1 y position
C color
Set a pixel value
slice( X1 Number, Y1 Number, R Number, start Number, stop Number, color Number) returns Boolean
X1 start point
Y1 start point
R radius
start start angle (radians)
stop stop angle (radians)
color Color index
Draws a filled pie slice
write( out Stream) returns Boolean
out destination file or web connection
Writes a GIF file

Index

Functions

add( value String)
value Key value
Appends a key to the next slot in the index
find( value String) returns Number
value Key value
Returns the index of one entry matching the key value, or -1 if the key is not in the index.
rebuild( )
Rebuilds an index created by Table.index().

Mail

Properties

nameString connection string

Functions

Mail( type String, login String, password String, server String, smtpserver String, language String, return address String) returns Mail
type mail system type: one of CCMAIL5, CCMAIL8, CCMAIL, BEYONDMAIL, VIM, NOTES, MAPI, MSMAIL, EXCHANGE, GROUPWISE, CMC, INTERNET, POP3, SMTP
login account name
password password
server server address or windows mail profile
smtpserver Internet mail server, if different from the POP3 server
language MIME language string, like USASCII or ISO-8859-1
return address Return mail address (generally useful if sending mail)
Connects to a mail server. In the case of internet mail (INTERNET, POP3, SMTP are equivalent), the password is unnessary. The return email address is login@server.
get( ) returns Table
Returns a message summary table. The table has a getMessage() function you can use to retrieve the message text. If the Mail system is closed, this table will be deactivated.
send( recipient String, subject String, textNote String, htmlNote String) returns Boolean
recipient comma-delimited list of recipient email addresses
subject subject line
textNote note
htmlNote HTML version of note (Internet mail only)
Sends a mail message.
sendFiles( recipient String, subject String, attachments String, textNote String, htmlNote String) returns Boolean
recipient comma-delimited list of recipient email addresses
subject subject line
attachments comma-delimited list of files
textNote note
htmlNote HTML version of note (Internet mail only)
Sends a mail message with file attachments.

Matrix

include('matrix.js')

Properties

colsNumber Number of columns
dataArray Number of columns
rowsNumber Number of rows

Functions

Matrix( data String)
Constructs a new matrix, where rows are separated by , and columns by spaces. new Matrix("1 0, 0 1") is the 2x2 identity.
Matrix( rows Number, cols Number, data Array|Numbers)
rows Number of rows
cols Number of columns
data Initial data
Constructs a new matrix, using data as its elements (in row-major order). You can pass a Numbers object if you plan to work with a lot of data.
Matrix.fit( O Integer, data Matrix) returns Array
Fits the Nx2 data to a polynomial of order O. Returns an array C such that the x^p coefficient of the least-squares fit is C[p].
Matrix.identity( N Integer)
Returns a new NxN identity matrix
Matrix.solve( S Matrix, Y Matrix)
Given a square matrix S and vector Y, returns X such that S · X = Y
at( row Integer, column Integer) returns Number
Same as get()
copy( ) returns Matrix
Returns a copy of the matrix.
get( row Integer, column Integer) returns Number
Returns the entry at row,column. No bounds-checking.
put( row Integer, column Integer, value Number) returns Number
Same as set()
set( row Integer, column Integer, value Number) returns Number
Updates the entry at row,column. No bounds-checking.
times( A Matrix, B Matrix) returns Matrix
Returns A · B.
toSource( ) returns String
toString( ) returns String
transpose( ) returns Matrix
Returns the transpose of the matrix.
zero( )
Resets the matrix to all zeros

Numbers

Fast and efficient ordered list of 64-bit floating point numbers. Numbers acts like Array, providing for .. in and [] operators, but the get() and set() functions are much more efficient.

Properties

lengthInteger Number of elements in this list.

Functions

Numbers( values String)
Creates a new array, initialized by converting values to numbers. Space, comma, or tab are good delimiters, but other characters will work, too, with a slight performance penalty.
Numbers( length Integer)
Creates a new array, initialized to 0.
Numbers( source Numbers)
Creates a new array, copying an existing Numbers object.
add( value )
Increments each list element by value
at( index Integer) returns Number
Same as get()
close( )
Immediately frees the memory used for this object
exec( )
This is a special function for doing fast vector operations with a RPN evaluator. Each parameter passed to this function may be a Numbers object (all of the same length!) or a String naming the mathematical operation. In the example
a = new Numbers(5)
b = new Numbers("1 2 3 4 5")
c = new Numbers("10 20 30 40 50")
a.exec(b,c,'+')
writeln(a)
the result is
11,22,33,44,55

The calculator stack starts as (b, c, '+'), and the result is stored in a (the object that called exec()). Arguments are evaluated left-to-right, so a is always the result of each operation and the number on the bottom of the stack for the next operation
You can also do
a = new Numbers("1 2 3 4 5")
b = new Numbers("10 20 30 40 50")
a.exec(b,'+')
writeln(a)
with the same result -- in case of stack underflow, the object calling exec() is pushed to the bottom of the stack.
This function may have as many arguments as you want, so long as all the lists are of the same length. The supported operators, and the number of arguments they take, are:
  • + 2
  • * 2
  • - 2 (or 1 for negation)
  • / 2 (or 1 for inversion)
  • cos 1
  • sin 1
  • tan 1
  • atan2 2
  • atan 1
  • pow 2
  • exp 1
  • log 1
    Special: unary negation and division (inversion) are allowed, as a shortcut
get( index Integer) returns Number
Returns the number at the index location. Throws an error if index is out of bounds.
log( )
Replaces each list element by its log (base e)
max( start Integer, length Integer)
Returns the index of the largest value in the list. Use start and length to operate on a subset of the list.
min( start Integer, length Integer)
Returns the index of the smallest value in the list. Use start and length to operate on a subset of the list.
pow( p )
Raise each list element to the power p
put( index Integer, value Number) returns Number
Same as set()
resize( length Integer)
Changes the length of the underlying list. If the length increases, new memory is allocated. If the length decreases, memory is not freed (but subsequent growth, up to the original length, will not use lead to a memory allocation). New entries are initialized to 0.
scale( value )
Multiplies each list element by value
set( index Integer, value Number) returns Number
Updates the number at the index location. Throws an error if index is out of bounds.
sum( start Integer, length Integer)
Returns the sum of all the numbers in the list. Use start and length to operate on a subset of the list.
sum2( start Integer, length Integer)
Returns the sum of the square of all the numbers in the list. Use start and length to operate on a subset of the list. Why would you want to do this? To calculate the standard deviation quickly.
var n = new Numbers("1 495 52 2 34 5 6 1 12 35 6 2 34")
writeln("Average: ",n.sum()/n.length)
writeln("Average of the square: ", n.sum2()/n.length)
toString( delimiter string, start Integer, length Integer) returns String
Although the Numbers class acts like the JavaScript Array class by default, you may customize the formatting with any delimiter (default is a comma). Use start and length to operate on a subset of the list.

ODBC

Properties

classNameString "ODBC"
errorString The last error message. It is initially undefined, and only changes when a query() or exec() function fails.
nameString Driver name

Functions

ODBC( connection string String) returns ODBC
connection string "DSN=source_name;UID=login;PWD=password;"
Connects to an ODBC driver. You can also use
var myDB = new ODBC("DRIVER={MySQL ODBC 3.51 Driver};SERVER=localhost;DATABASE=dbname;USER=root;PASSWORD=password;OPTION=3;");
var myReader = myDB.query('select * from people');
or
var myT = new Table('odbc://DRIVER={MySQL ODBC 3.51 Driver};SERVER=localhost;DATABASE=dbname;USER=root;PASSWORD=password;OPTION=3;/people')
The difference is that the query() function gives you a read-only table, while the Table() constructor lets you make changes with set() and setRow().
You might see a "Dialog failed" message from Microsoft. This only means that there's something wrong with your connection string.
JSDB is a mediocre command-line SQL console. Use Raosoft's SQL.exe instead.
close( ) returns Boolean
Closes the connection to the database and all tables that were opened with the query() function. The table objects are invalidated (further function calls will fail), but they are not deleted.
exec( command String) returns Boolean
command "ALTER TABLE ..."
This calls SQLExecDirect() on the database. Returns true if the operation was successful. You can read the error parameter to find out what went wrong otherwise.
query( query String) returns Table
query "SELECT * FROM table WHERE ..."
Executes an SQL command, and returns the result set mapped into a read-only Table object. The Table object provides a cache and indexed access to records, even if the ODBC driver does not. If you just want to read from a SQL table with a simple query, this is equivalent to new Table('odbc://userid:password@service/tablename?field1=xxx*&field2=yyy'). Both ways of accessing the tables do on-demand loading of data from the database server.

Process

Properties

activeBoolean Whether the program is still running.
classNameString "Process"

Functions

Process( cmd String)
cmd Command line, .exe file name, or document name
The constructor tries to start a program. Only programs ending in .exe will be run. If cmd is a document file or URL, Process queries the Windows shell to run the appropriate program to open the document. Note that file names must be fully qualified.
close( )
Sends a quit message to the child process and frees associated handles.

Record

Properties

caseSensitiveBoolean Are fields case sensitive?
countNumber Number of name-value pairs stored by the record
lengthNumber Number of name-value pairs stored by the record

Functions

Record( initial String, delimiter String) returns Record
initial Delimited string for initial values (a=b,c=d,e=f,...)
delimiter Delimiter character, default is a comma
Creates a record with initial values. See read().
Record( caseSensitive Boolean) returns Record
caseSensitive true for a case-sensitive list
Creates a record. Use Record(true) for name searches to be case-sensitive.
append( data Record) returns Number
data Additional data
Appends the name/value pairs from another record. If field names match, they are overwritten.
clear( ) returns Boolean
Deletes all the name/value pairs from the record.
get( name String) returns String
name Field name
Returns the value of a field, or an empty string if the field does not exist.
has( name String) returns Boolean
name Field name
Returns true if the field exists in the record.
name( index Number) returns String
index Index from 0 to length
Name/value pairs are indexed sequentially. This function returns the name at a given position.
read( data String, delimiter String) returns Number
data Delimited string to read (a=b&c=d&e=f&...)
delimiter Delimiter character, default is & (think of HTTP GET)
Reads a delimited string into the record.
readINI( file String, file String) returns Number
file INI file name (in Windows directory by default)
file INI file section
Reads a Windows INI file section.Returns the number of entries.
set( name String|Integer, value String) returns Boolean
name Field name or index
value New value
Sets a field value, or creates a name/value pair if it doesn't already exist.
toString( ) returns String
Returns a '\n'-delimited list of the record.
unSet( name String) returns Boolean
name Field name
Removes a name/value pair if it exists.
value( index Number) returns String
index Index from 0 to length
Name/value pairs are indexed sequentially. This function returns the value at a given position.
write( delimiter String) returns String
delimiter Delimiter character, default is & (think of HTTP GET)
Returns a delimited string of the record's name-value pairs.
writeINI( file String, file String) returns Number
file INI file name (in Windows directory by default)
file INI file section
Writes a Windows INI file section. Returns the number of entries.

Server

Properties

anyoneWaitingBoolean is a client waiting for a response?
hostNameBoolean
portBoolean

Functions

Server( port Number) returns Server
port Default port is 80.
accept( ) returns Stream
Accepts the next connection in the input queue and returns a Stream pointer to communicate with it.
close( ) returns Boolean
Closes the server and all connections.
toString( ) returns String
Describes the server configuration and port.

Stream

Properties

canReadBoolean True if there are characters available in the input buffer, or if you haven't reached the end of a memory stream.
canWriteBoolean True if the stream was created for writing.
eofBoolean Is the stream at its end? For COM streams, this identifies whether the stream has been closed. Network streams (http://, net://) can only detect whether they've been closed after a read() or write() call returns 0. While eof can detect socket error conditions, this doesn't happen very often. Unfortunately, there's no good way to detect if a network socket is closed without reading or writing to it.
hasChildrenBoolean See readTag()
nameString Filename or URL
posNumber Same as position
positionNumber Cursor position, in bytes, from the beginning. This property is not appropriate for HTTP and COM streams.
sizeNumber Total number of bytes for file and memory streams.
statusString|Number Web server response status message, such as 'HTTP/1.1 200 OK'.
stderrStream Captures stderr output from exec://
tagTextString See readTag()

Functions

Stream( name String, type String) returns Stream
name Filename, URL, Number of bytes for a memory stream. URLs are of the form:
http://www.jsdb.org/
file://c:/test.txt
net://server.com:port
com1://56000 (or com2, com3, ...)
text://number_of_bytes
temp://number_of_bytes
exec://command line
type For files, the open mode (rwactb+). A + indicates an unbuffered stream and a b indicates binary mode. The default mode is 'rt' (read a text file).
File modeDescriptionCombie with
aAppend to a file or write-only file device. You can not seek, so you can not read.+tb
rwCreate a new file or open an existing file with read and write access+tb
wCreate or replace a file with read and write access+tbr
rOpen an existing file with read access+tbw
tText mode: \r is stripped when reading, and \n is converted to \r\n when writing. seek and pos are accurate.arw+
bBinary mode: no CRLF mapping.arw+
+Unbuffered: does not use read-ahead or write-behind cache.arwtb
dPipes only: Creates a detached process with its own console window.(none)

If this parameter is omitted, a http:// url will use Internet Explorer's proxy settings and de-chunk "Transfer-encoding: Chunked" transmissions (often created by Apache CGI) for you. If this parameter is set to 0, JSDB will not use the proxy, nor will it de-chunk the stream. But the "status" parameter will be set to the complete HTTP status line (HTTP/1.1 200 OK), and not just the status code (200). In either case, you'll want to use Record.readMIME(stream) to parse the HTTP headers before reading the file contents.

By default, net:// streams set the TCP_NODELAY option. Set this parameter to 0 to disable TCP_NODELAY. This will default to the Nagle algorithm that groups short write() calls so as to send fewer packets.

If name is a string, jsdb will first try to open a URL.
To retrieve a web page using GET and standard headers, use Stream('http://server.com/'). The status property will be initialized with the first line from the server response.
To simply open a socket to the server and send your own headers, use a = new Stream('net://server.com:80/'); a.writeln('POST /file.cgi/ HTTP/1.1\r\n'). The port number defaults to 80 if it is omitted.
A file:// URL is always opened in binary, read-only mode.
If name does not appear to be a URL (no ://), jsdb will try to open a file instead. Forward slashes are converted to back slashes when opening files in Windows.
If name is omitted or is a number, an in-memory stream will be created, with the initial length given by name.

If name starts with "exec://", the stream returns a pipe to a spawned process. Try this:

p = new Stream("exec://jsdb.exe","d")
p.writeln("writeln('hello world');")
writeln(p.readln())
p.writeln("quit");
append( data Stream, length Number) returns String
data Stream to append
length Max number of bytes to read
Appends bytes from data until its end. Remember to rewind data before using it in a call to append()!
appendText( data Stream, length Number) returns String
data Stream to append
length Max number of bytes to read
Like append(), but maps '\n' to \r\n'. This is used to prepare text for a windows edit control.
clear( ) returns Boolean
Resets a memory stream. The length is set to zero, and the position returned to the beginning, but memory is not freed.
eatChars( skip String) returns String
skip Characters to skip
Reads the stream one byte at a time. If a byte is not in the skip string, it returns a string containing that byte. A null character always stops the scan. Example: var lastchar = file.eatChars(' \t\r\n')
format( source Stream|String, values Record, start_delimiter String, end_delimiter String)
Reads format and replaces {fieldname} with appropriate record values. The standard delimiters, are curly braces, but you can override these with any text string. If end_delimiter is null and start_delimiter is non-null, end_delimiter = start_delimiter.
get( ) returns String
Reads one byte from the stream and advances the cursor.
goBack( offset Number) returns String
Moves the cursor backward offset bytes from the current position..
goForward( offset Number) returns String
Moves the cursor forward offset bytes from the current position.
peek( ) returns String
Returns the next byte in the file or memory stream, without advancing the cursor. Since HTTP and COM streams aren't buffered, you should avoid using this function unless you know the source of the stream.
put( ) returns String
Writes one byte to the stream and advances the cursor.
putBack( offset Number) returns String
Moves the cursor backward offset bytes from the current position..
read( count Number, dest Stream) returns String
count number of bytes
dest Optional target for retrieved data
Reads up to a fixed number of bytes from a file, and returns them as a string. If dest is provided, readFile() runs instead of read()
readByte( ) returns Number
Same as readUInt8()
readFile( size Number, dest Stream) returns String|Number
size Maximum number of bytes
dest Where to store the data
Reads the entire stream into a string in binary mode. size and dest may be in any order. If dest is provided, the return value is the number of bytes actually copied. Otherwise, the return value is a string. The stream is read in binary mode, so the string may contain embedded nulls.
readInt( swap Boolean) returns Number
swap Swap byte order?
Reads a binary, signed 32-bit integer in Intel byte format. (JavaScript uses 31 bit integers internally)
readInt16( swap Boolean) returns Number
swap Swap byte order?
Reads a binary, signed 16-bit integer in Intel byte format.
readInt32( swap Boolean) returns Number
swap Swap byte order?
Same as readInt().
readInt8( ) returns Number
Reads a binary, signed 8-bit integer.
readLine( ) returns String
Same as readln.
readList( data Record, delimiter String, equals String) returns Number
data Data to write
delimiter Delimiter to use (default is probably "\n", but is not guaranteed)
equals Name/value separator (default is "=")
Reads a delimited name-value list. The delimiter and equals sign must be single characters. Note that "\r\n" in files is mapped to "\n" in memory, so the default input it expects is name=value name1=value1 name2=value2 Returns the number of pairs read.
readListB( data Record) returns String
Reads data from a Record in binary format.
readMIME( data Record) returns Number
data Data to write
Reads a name-value list in MIME format. This takes whitespace after the colon into account, and assumes that any non-blank line beginning with whitespace is a continuation line. Returns the number of pairs read.
readTag( data Record, allowed String) returns String
data Tag fields
allowed Comma-delimited list of allowed fields, case-sensitive
Used for parsing XML files. This function scans forward in a file until a markup tag is found. If allowed is given, only tags (and end-tags) in the list will stop a scan. Otherwise, any < sign stops the scan. The text skipped in this scan is stored in the stream's parameter tagText.
When it reaches a tag, it reads the tag parameters, and stores them in data. The XML escape sequences < > & and " are automatically decoded in the parameters, but not in CDATA sections.
If the tag has an end marker, (ex: <tag field=value />), the stream's parameter hasChildren is set to false. Otherwise, hasChildren is true. The tag name is returned. If the end of the file has been reached, the return value is an empty string.
If the tag name is "![CDATA[", readTag() searches forward for "]]>", and appends the intervening text to tagText.
For an example of how this is used, see the module "xml.js". var params = new Record; var name = stream.readTag(params,allowed);
readText( ) returns String
Reads the entire stream, converting all linefeeds to \r\n. Returns a string of the result.
readUInt16( swap Boolean) returns Number
swap Swap byte order?
Reads a binary, unsigned 16-bit integer in Intel byte format.
readUInt8( ) returns Number
Reads a binary, unsigned 8-bit integer.
readUntil( search String, skipped Stream) returns Boolean
search String that stops the search
skipped Skipped data is written to this stream
Returns true if the search string was found. readUntil() does a case-insensitive text search. For a binary search, use readUntilBytes(). If search is a unicode string, it will be converted to UTF-8. Example: var memory = new Stream var file = new Stream('test.txt') file.readUntil('</file>',memory) writeln(memory)
readUntilBytes( search String, skipped Stream) returns Boolean
search Byte pattern that stops te search
skipped Skipped data is written to this stream
The binary version of readUntil(), readUntilBytes() can search for patterns with embedded nulls.
readln( delimiter String) returns String
delimiter End-of-line character (default '\n')
Returns the next line in the file. At the end of the file, it returns an empty string "".
resize( size Number) returns String
size Specifies the new buffer size
Resizes a memory stream. If the stream decreases, data are truncated from the end. If the cursor is beyond the end of the stream, it is moved to the new end. If the stream is expanded, memory is allocated, but no new data are added.
rewind( ) returns String
For file and memory streams, moves the cursor to the beginning of the stream. Example: temp = new Stream temp.write('hello, world') temp.rewind() file = new Stream('test.txt','at') file.append(temp)
seek( location Number) returns String
Moves the cursor to a new offset from the beginning.
setEndOfFile( length Number) returns Boolean
length New maximum file length
Changes the length of a a file or memory stream. Memory streams can be truncated. File streams can be truncated or extended.
toString( ) returns String
For a file, COM, or HTTP stream, this returns the filename. For a memory stream, it returns the entire buffer.
write( data... String) returns Number
data... Objects to write to the stream
Example: stream.write('hello', '4', 5). If the parameters to this function are not strings, their toString() function will be called. Returns the number of bytes written.
writeByte( value Number) returns Number
Same as writeUInt8
writeInt( value Number, swap Boolean) returns Number
swap Swap byte order?
Writes a binary, signed 32-bit integer in Intel byte format.
writeInt16( value Number, swap Boolean) returns Number
swap Swap byte order?
Writes a binary, signed 16-bit integer in Intel byte format.
writeInt32( value Number, swap Boolean) returns Number
swap Swap byte order?
Same as writeInt().
writeInt8( value Number) returns Number
Writes a binary, signed 8-bit integer.
writeLine( ) returns String
Same as writeln.
writeList( data Record, delimiter String, equals String) returns Number
data Data to write
delimiter Delimiter to use (default is probably "/", but is not guaranteed)
equals Name/value separator (default is "=")
Writes a delimited name-value list. You can specify any string to use for the record and field delimiters. Default output is name=value/name1=value1/name2=value2/... Returns the number of pairs written.
writeListB( data Record) returns String
Writes data from a Record in binary format. The C++ equivalent is for (int i=0; i< data.count; i++) { fwrite(data[i].name,1,strlen(data[i].name) + 1, file); fwrite(data[i].value,1,strlen(data[i].value) + 1, file); } fwrite("",1,1,file);
writeMIME( data Record) returns Number
data Data to write
Writes a name-value list in MIME format. This is equivalent to writeList(data,': ','\n'). A blank line ends the list. Returns the number of pairs written.
writeUInt16( value Number, swap Boolean) returns Number
swap Swap byte order?
Writes a binary, unsigned 16-bit integer in Intel byte format.
writeUInt8( value Number) returns Number
Writes a binary, unsigned 8-bit integer.
writeln( ) returns String
Like write(), but appends a newline (\n for memory, \r\n for files). The file I/O system ensures that, for text mode files, \n in memory is faithfully mapped to \r\n on disk. You can use pos and seek() to move the cursor in text files, but do not rely on counting the bytes in read() and write() operations.

Table

Properties

classNameString "Table"
colCountNumber number of columns
Column numbers start at 1, and 0 indicates an invalid column.
countNumber same as rowCount
errorString last error message
lengthNumber same as rowCount
nameString the filename of the table
rowCountNumber number of rows
Row numbers start at 1, and 0 indicates an invalid row.

Functions

Table( name String) returns Table
name data source name, of the form
drive:/directory/filename.asc
drive:/directory/filename.dbf
odbc://login:password@data_source/table
notes://login:password@server/table (not available yet)
Opens a table. The data source name may be blank to create an in-memory spreadsheet.
add( data Record) returns Boolean
data initial values
Adds a new row to the table, populating it with values from data, and returning the number of the new row.
SQL databases:
  • JSDB will not set autoincrement fields in INSERT statements. Your database does this for you.
  • If you have a key field which is not set and not autoincrement, JSDB will generate a unique 24-character value, based on the system time and a counter stored in the registry. This value will not repeat in the lifetime of the solar system.
  • If you are adding to an Oracle table and do not provide a primary key value, JSDB will use seq_tablename.nextval.
addColumn( name String) returns Boolean
name column name
Adds a new column, which must have a unique name, and returns the new column's number.
column( column String) returns Number
column field name
This finds the column number corresponding to a field name. If the field name does not exist in the database, the return value is zero.
data( row Number, column Number|String) returns String
row row number (starting with 1)
column column number or name
Returns text data at a position in the table. You can determine if a row is marked deleted if the first character of table.data(row,0) is 'D'.
del( data Number) returns Boolean
data row number
Deletes a row from the table.
deleteColumn( column Number) returns Boolean
column column number
Removes a column from a spreadsheet table.
error( ) returns String
Stores the last error message returned by the table. This is useful for debugging SQL tables.
find( query Record, start Number, direction Number) returns Number
query values to search for, for example:
query = new Record('name=Alice');
row = table.find(query)
start row number from which to start searching (defaults to the first row)
direction +1 to search forward, or -1 to search backwards
The result of the last search is stored in the table's lastFind property. Deleted rows are skipped during the search.
findNext( query Record) returns Number
query query from find()
Continues the last search.
get( row Number, column Number|String) returns String
row row number (starting with 1)
column column number or name
Same as data()
getMessage( row Number) returns String
row row number (starting with 1);
For mail message tables, returns the message text.
getRow( row Number, data Record) returns Boolean|Record
row row number
data data values
Returns a record containing the values from a row in the table. If the "data" parameter is used, then it is filled with the values and the function returns true or false.
index( column String|Number) returns Index
column Column name
This function returns an index to the database. If you call index() with a single column name or number, the returned object will have find(key) function, where key can be either a field value or a Record containing the appropriate field value.
If you call index() with a list of field names, the index will be built from strings where data values are separated by newlines. Therefore, you can call index().find('value1\nvalue2\nvalue3') or index().find(new Record('field1=value1,field2=value2,field3=value3').
The index().find() function returns the number of a matching row, or -1 if none are found.
Since it takes time to build the index, you can do something like this:
var index = table.index('field')
writeln('adding record ',table.addRow(data))
index.add(data)
writeln('found record ',index.find(data));
save( file String|Stream, delimiter String, titles Boolean) returns Boolean
file file name
delimiter Defaults to the delimiter used to read the file or tab
titles Defaults to true
Save databsae changes. If the database has no file name, the function fails. For ODBC databases, this forces a COMMIT statement. For DBF databases, nothing happens.
For ASCII databases, you can save to a file name or a stream. In this case, you select a delimiter (or null for the default) and choose whether to include the header row.
set( row Number, column Number|String, value String) returns Boolean
row row number (starting with 1)
column column number or name
value new value
Set text data at a position in the table. You can delete a row with table.set(row,0,'Delete') With DBF and SQL tables, you can un-delete a row with table.set(row,0,' ') DBF tables do not remove deleted rows. SQL tables remove deleted rows when they refresh, which is not necessarily immediate. Spreadsheets delete rows immediately.
setN( row Number, column Number|String, value Number) returns Boolean
row row number (starting with 1)
column column number or name
value new value
Set number data at a position in the table. The number will usually be converted to text to store it in the database.
setRow( row Number, data Record) returns Boolean
row row number
data data values
Sets data values into the table. Returns true on success.
setTitle( column Number, title String) returns Boolean
column column number
title new title
Changes a column's title. This only works for spreadsheet (ASCII and in-memory) tables.
title( column Number) returns Number
column column number
Returns the title of a column. Column numbers start at 1. You can find the number of columns in a table from the colCount property.
toString( ) returns String
Returns the file name
type( column String|Number) returns String|Array
column Column name
For one argument, this returns the data type corresponding to the row. For several arguments, this returns an array of data types. The possible types are C, N, D, T for Character, Number, Date, and Time.
width( column Number) returns Number
column column number
Returns the width, in characters, of data that may be stored in this column. Spreadsheet tables do not have a width limit.

XML

include('xml.js')

Standard usage: XML.read(stream,allowed_tags)

Properties

cdataString
childrenArray
nameString
paramsRecord

Functions

find( type String, parameter String, value String) returns Array
type Child class
parameter Field name
value Field value
Returns an array of all the child objects whose name is equivalent (case-sensitive) to type
findChildren( type String, parameter String, value String) returns Array
type Child class. If omitted, searches all children
parameter Field name. If omitted, skips the field comparison
value Field value
(Deprecated) Returns an array of all the child objects whose name is equivalent (case-sensitive) to type and which has a matching field value. Example: fn.find('parameter','optional','1') returns the list of optional parameters for the XML file that generates this document. Use XML.find() to return a list of all the children
get( name String) returns String
name Parameter name
Returns the field value corresponding to name. If the field value is missing, this returns an empty string. To test for the existence of a field, use params.has('name').
getChildren( type String) returns Array
type Child class
(Deprecated) Returns an array of all the child objects whose name is equivalent (case-sensitive) to type
read( source Stream, dtd String, ignored String, start XML) returns Boolean
dtd comma-delimited list of tag names
ignored comma-delimited list of tags to ignore (defaults to BR,P,B,I,C,TT,U,IMG,A)
start an existing XML object to receive the new XML tags
This is a static function. Usage: xml.read(stream, 'html,head,body,p')
sort( field String, descending Boolean)
field Field to sort by
descending Reverse order? (Default false)
Sorts the children array, according to the value in a given field.
toStream( output Stream) returns String
output Appends the XML object to a stream.
toString( ) returns String
Appends the XML object to a memory stream, then returns a string.

global

Properties

jsArgumentsArray Also available as system.arguments. A list of command line arguments (as strings)

Functions

attributes( filename ) returns String
Returns an object describing the specified file. { attributes: String, size: Number, date: Date, creation: Date } On Windows, attributes can include "archive, compressed, directory, hidden, offline, readonly, system, temporary". On Unix, attributes can include "directory, symlink, regular, chardev, blockdev, fifo, socket".
copyFile( source String, destination String) returns Boolean
Deprecated. Use system.copy() instead. Copies files. Fails if the destination file exists.
crc32( text , seed ) returns Number
Calculates the 32-bit CRC of a text string. The initial seed may be specified. The parameters may be passed in any order.
decodeANSI( text String) returns String
Converts a Windows-1252 (ANSI) string to a JS string (UCS-2)
decodeB64( in Stream|String, out Stream) returns Number
Applies base-64 (MIME) decoding and sends the result to out. Returns the size of the decoded data.
decodeB64( text String) returns String
Removes base-64 (MIME) encoding and returns an decoded string.
decodeHTML( text String) returns String
Removes & encoding and returns an decoded string. It decodes < > " & and &#XXX; sequences
decodeURL( text String) returns String
Decodes a URL-encoded string.
decodeUTF8( text String) returns String
Converts UTF-8 string to a JS string (UCS-2)
encodeB64( text String) returns String
Applies base-64 (MIME) encoding and returns an encoded string.
encodeB64( in Stream|String, out Stream) returns Boolean
Applies base-64 (MIME) encoding and sends the result to out. Returns the size of the encoded data.
encodeHTML( text String) returns String
For XML and HTML printing, applies & encoding and returns an encoded string. It encodes < > " & and Unicode character values over 127.
encodeURL( text String) returns String
Applies URL (%) encoding and returns an encoded string. Alphanumeric and punctuation characters used in URLs are not translated.
encodeUTF8( text String) returns String
Converts a JS string (UCS-2) to UTF-8
fileExists( file )
Deprecated. Use system.exists() instead. Returns true if the file exists and is available for reading.
jsBuildDate( ) returns String
Deprecated. Use system.buildDate() instead. Returns a string containing the build date of the JavaScript interpreter.
jsDebug( address String) returns Boolean
address Debugger address
Deprecated. Use system.debug() instead. Connects to a remote debugger. jsDebug('127.0.0.1:1002')
jsGC( ) returns Null
Deprecated. Use system.gc() instead. Runs garbage collection
jsIsSafe( ) returns Boolean
Deprecated. Use system.isSafe() instead. Tells whether the interpreter is in safe mode.
jsOptions( options String) returns String
options 'strict' or 'werror' (treat warnings as errors)
Deprecated. Use system.options() instead. Toggles the interpreter options, and returns a comma-delimited string of the currently set options. By default, strict is active at startup.
jsRestart( )
Deprecated. Use system.restart() instead. Sets the "shouldStop" flag to true, and instructs the interpreter to repeat execution. This is only used in the XYKE web server.
jsSafeMode( code Number) returns Number
code password
Deprecated. Use system.safeMode() instead. Sets a flag in the interpreter to indicate that file access should be forbidden while running an untrusted piece of code. The first call to jsSafeMode() returns a pseudo-random number, and locks file access. The second call, to unlock file access, must be of the form jsSafeMode(number), where the first parameter is the number returned by the call to jsSafeMode() that locked file access. In safe mode, email is blocked, and only memory streams and http:// streams may be created. File and serial port streams that were opened outside of safe mode may still be accessed.
jsShellExec( command String, dir String)
command shell command line
dir working directory
Deprecated. Use system.execute() instead. Calls ShellExec() on Windows, or system() on UNIX.
jsShouldStop( )
Deprecated. Use system.shouldStop() instead. Returns true if the script should finish.
jsVersion( new version Integer) returns String
new version New interpreter version number
Deprecated. Use system.version() instead. Returns a string containing the JavaScript interpreter version number (or the previous version, if the version is changing). The default version is presently 1.5. The version codes are defined as
    JSVERSION_1_0     = 100,
    JSVERSION_1_1     = 110,
    JSVERSION_1_2     = 120,
    JSVERSION_1_3     = 130,
    JSVERSION_1_4     = 140,
    JSVERSION_ECMA_3  = 148,
    JSVERSION_1_5     = 150,
    JSVERSION_DEFAULT = 0,
    JSVERSION_UNKNOWN = -1
kbhit( ) returns Boolean
Returns true if console input is available.
listFiles( filespec )
filespec defaults to "*.*"
Deprecated. Use system.files() instead. Returns an array of file names. Directories and are excluded. System files, hidden files, and names beginning with . are excluded.
listFolders( filespec )
filespec defaults to "*.*"
Deprecated. Use system.folders() instead. Returns an array of directory names. Files are excluded. System folders, hidden folders, and names beginning with . are excluded.
load( filename ) returns Boolean
Runs a JavaScript file. JSDB looks first for files with the following precedence:
  1. In a ZIP archive appended to the program file. (This only works on UNIX if the program file is in the current directory.)
  2. In the current working directory
  3. In the library path. (Set this on the command line with -path, defaults to the executable's directory)
  4. JSDB ignores the system's path and will not run files from unusual directories.
    This order is chosen so that you may override the standard JSDB libraries, but carries certain security risks. For instance, someone might write a malicious "xml.js" in the current directory, expecing that library to be loaded by another script later. Therefore, you should be careful about calling the system.cwd() function.
    As with run(), load() will fail if JSDB is in safe mode.
    Unlike run(), load() will only execute a given source file only once. Files will be reloaded if they have been modified.
loadResource( name ) returns Stream
Deprecated. Use system.resource() instead. Returns a readable stream containing the resource data. The resource file is either in the ZIP file attached to or in the same directory as the interpreter program. Deprecated. Use system.resource() instead.
moveFile( source String, destination String)
Deprecated. Use system.move() instead. Moves a file. Fails if the destination file exists.
openBrowser( file )
file URL
Deprecated. Use system.browse() instead.
print, write( )
Prints the parameters to stdout, calling toString() if necessary.
printReport( format Stream, values Record) returns String
Deprecated. Reads format and replaces {fieldname} with appropriate record values.
println, writeln( )
Like print() and write(), but writes CR/LF at the end.
quit,exit( )
Deprecated. Use system.quit() or system.exit() instead. Sets the "shouldStop" flag to true. Execution does not stop immediately.
readln( end String) returns String
end Line end marker, defaults to \n
Reads a line from stdin. Console mode only.
regGetKey( section , name )
section "hkey_local_machine\SOFTWARE\..."
name Key name
Deprecated. Use system.getKey() instead. Returns a string containing the registry data.
regSetKey( section , name , value )
section "hkey_local_machine\SOFTWARE\..."
name Key name
value Key value
Deprecated. Use system.setKey() instead. Sets a registry entry. Returns true if successful.
run( filename )
Runs a JavaScript file. Run uses the same file-finding rules as load().
run( text Stream, filename String, line Number)
Runs JavaScript code stored in a stream. The functions run() and load() are equivalent
sleep( time Number)
time milliseconds
Deprecated. Use system.sleep() instead. Suspends the process and yields control to other programs.
splitURL( URL String) returns Array
Parses a URL of the form service://user:password@host/file?query, and returns an array of strings: [service, user, password, host, file, query]
stripWhitespace( text String) returns String
Returns a string with initial and final whitespace characters removed.
testCompile( code ) returns String
code JS code to test
Deprecated. Use system.compile() instead. Returns whatever error messages if there's a problem compiling the code.

system

Properties

argumentsArray A list of command line arguments (as strings)
buildDateString Interpreter build date.
releaseNumber The JSDB release number, something like "1.3".
stdinStream Use system.stdin to read directly from the console. The stream is unbuffered.
stdoutStream Use system.stdout to write directly to the console. The stream is unbuffered. The interpreter always sends error messages to stdout, never to stderr.
versionNumber Divide by 100 to get the language version. JavaScript 1.5 is represented as 150.

Functions

browse()( file )
file URL
Opens the default web browser on the console, and points it to the specified URL.
buildDate( ) returns String
Returns a string containing the build date of the JavaScript interpreter.
compile( code ) returns String
code JS code to test
Returns error messages if there's a problem compiling the code.
copy( source String, destination String) returns Boolean
Copies files. Fails if the destination file exists.
debug( address String) returns Boolean
address Debugger address
Connects to a remote debugger. system.debug('127.0.0.1:1002')
execute( command String, dir String)
command shell command line
dir working directory
Calls ShellExec() on Windows, or system() on UNIX.
exists( file )
Returns true if the file exists and is available for reading.
exit( )
Sets the "shouldStop" flag to true. Execution does not stop immediately.
files( filespec )
filespec defaults to "*.*"
Returns an array of file names. Directories and are excluded. System files, hidden files, and names beginning with . are excluded.
folders( filespec )
filespec defaults to "*.*"
Returns an array of directory names. Files are excluded. System folders, hidden folders, and names beginning with . are excluded.
gc( ) returns Null
Runs garbage collection.
getKey( section , name )
section "hkey_local_machine\SOFTWARE\..."
name Key name
Returns a string containing the registry data. (Windows only)
getenv( name String) returns String
name variable name
Returns an environment variable.
help( ) returns String
Returns information about the interpreter version. Look for "JSDB 1.1 ...".
isSafe( ) returns Boolean
Tells whether the interpreter is in safe mode.
mkdir( directory )
Creates a directory (recursively). Always returns true.
move( source String, destination String, replace Boolean)
replace Set to true to overwrite existing files
Moves a file.
options( options String) returns String
options 'strict', 'werror' (treat warnings as errors), 'atline', 'xml' (enable E4X in subsequent load() and run() calls)
Toggles the interpreter options, and returns a comma-delimited string of the currently set options. By default, strict is active at startup.
print, write( )
Prints the parameters to stdout, calling toString() if necessary.
println, writeln( )
Like print() and write(), but writes CR/LF at the end.
quit( )
Sets the "shouldStop" flag to true. Execution does not stop immediately.
readln( end String) returns String
end Line end marker, defaults to \n
Reads a line from stdin. Console mode only.
resource( name ) returns Stream
Returns a readable stream containing the resource data. The resource file is either in the ZIP file attached to or in the same directory as the interpreter program.
restart( )
Sets the "shouldStop" flag to true, and instructs the interpreter to repeat execution.
safeMode( code Number) returns Number
code password
Sets a flag in the interpreter to indicate that file access should be forbidden while running an untrusted piece of code. The first call to jsSafeMode() returns a pseudo-random number, and locks file access. The second call, to unlock file access, must be of the form system.safeMode(number), where the first parameter is the number returned by the call to system.safeMode() that locked file access. In safe mode, email is blocked, and only memory streams and http:// streams may be created. File and serial port streams that were opened outside of safe mode may still be accessed.
setKey( section , name , value )
section "hkey_local_machine\SOFTWARE\..."
name Key name
value Key value
Sets a registry entry. Returns true if successful. (Windows only)
setcwd( directory ) returns String
Sets the current working directory (if directory is not empty) and returns the previous working directory.
shouldStop( )
Returns true if the script should finish.
sleep( time Number)
time milliseconds
Suspends the process and yields control to other programs.
stripWhitespace( text String) returns String
Returns a string with initial and final whitespace characters removed.