server-side JavaScript: Prototypes of built-in classes, objects and functins

G

GVDC

Prototypes of built-in classes, objects and functions available with server-side JavaScript
Contents of README_serverside_javascript_prototypes.txt Readme file:


Grom persistent interpreter connector
GromJS SpiderMonkey server-side JavaScript
--------------------------------------------------------------------------------

Manual includes prototypes of built-in classes, objects and functions available
with GromJS server-side JavaScript. In addition to this manual see sample
server-side JavaScript Web scripts provided in directory with this Readme.

The definitions of classes and objects and function prototypes are given in
pseudo-code.




--------------------------------------------------------------------------------
CONTENTS:
- Top level functions
- Cgi object (handles receival of client-sent data ie. GET/POST data,
uploaded files, cookies, etc, and provides metods for manipulation of
these values; see examples below)
- Server object (includes set of functions related to interpreter
process itself ie. getpid, various utility functions ie. getenv, time,
rand, FS manipulation ie. mkdir, rmdir, unlink, link, symlink, chmod
etc)
- Session object (disk-based session variables for data persistence
between script executions)
- File class (manipulation of files on server, ie. open, close, read,
write, seek, truncate, lock etc)
- Sqlite class (SQLite3 API ie. open, close, exec, query, fetchrow)
- Pipe class (executing external programs and communicating through Unix
pipe)
- Dictionary class (hash array, unlimited size, configurable
efficiency/speed)







TOP LEVEL FUNCTIONS:
--------------------------------------------------------------------------------
uint printf(string DATA [,string DATA2 ...]); //print arguments
void load(string SCRIPTPATH [,string SCRIPTPATH2 ...]); //load script(s) on SCRIPTPATH
void include(string SCRIPTPATH [,string SCRIPTPATH2 ...]); //same as "load"










CGI OBJECT:
--------------------------------------------------------------------------------
Built-in "Cgi" object provides access to client-sent data ie. query string, POST
data, uploaded files, cookies etc. SpiderMonkey interpreter is configured to
automatically output CGI response headers and Cgi.header() function is available
for setting arbitrary response-headers.

//prototype:
object Cgi {
//methods:
string query([string VARNAME] [, object DEFAULTVAL]); //used with no argument, returns whole querystring; with
argument VARNAME returns VARNAME's value; if variable not found returns empty string
string post([string VARNAME] [, object DEFAULTVAL]); //same as above, values searched in POST data
string any(string VARNAME [, object DEFAULTVAL]); //same as above; fetch from any available source,
querystring or POST data, in that order
//Methods Cgi.query() Cgi.post() Cgi.any() by default return an empty string if requested var not found
//Optional 2nd arg can be supplied which functions can return when var is not found, ie.:
//var myval = Cgi.any("myvar", null); //return null if myvar not found

array names(); //returns array of strings with all var names from querystring and postdata ie.
script called with URL such as "myscript.js?nam1=val1&nam2=val2" returns array containing "nam1", "nam2" .
void separators(string SEPARATORS); //use alternative separator (delimiter) chars for querystring/postdata; default
are "=" and "&" Example: Cgi.separator("=;") to use "=" and ";" as delimiters
string getcookie(string COOKIENAM); //get value of COOKIENAM (available in "HTTP_COOKIE" environment variable)
void header(string HEADER); //add arbitrary response header ie. Cgi.header("Content-Type: image/gif") ;

//properties:
array Files; //array of "Uploadedfile" objects; see "Uploadedfile" prototype below
};

//example:
//HTTP request querystring: /myscript.js?somevar=someval&myvar=myval
printf(Cgi.any("myvar") +"<br>"); //print value of "myvar"
printf(Cgi.getcookie("myid") +"<br>"); //print value of "myid" cookie


//prototype:
object Uploadedfile {
//properties
string name; //name of HTML form input field ie "myphoto1"
string filename; //filename on client's disk ie. "c:\files\myfile.gif" or "/files/myfile.gif"
string tmpfile; //location of newly created uploaded file ie. /tmp/fileupload23457742463624355325.dat
string type; //file type ie. image/gif
string encoding; //encoding
uint size; //size of uploaded file in bytes
};

//example:
//array length indicates the number of uploaded files
if ( Cgi.Files.length>0 ) {
var Uplfile = Cgi.Files[0]; //get 0'th Uploadedfile object
printf(Uplfile.name); //print the name of uploaded file
}










SERVER OBJECT:
--------------------------------------------------------------------------------
Built-in "Server" object includes a set of functions (methods) related to
JavaScript interpreter process itself such as process PID, errno, exit etc.,
various utility functions such as current time, rand etc., file-system
interaction functions ie. mkdir, chmod, stat, file copy, unlink etc.

//prototype:
object Server {
//methods:
void timeout(uint SECONDS); //script timeout; set max SECONDS allowed for script execution after which
process exits, ie. abort script in infinite loop
uint sleep(uint SECONDS); //put process to sleep for SECONDS seconds
void gc(); //run garbage-collector; Ie. after many vars used, large arrays, database
reads/writes etc.
void buffer(uint BUFFER); //output buffer; 0 == no buffer, output is sent immediately; non-zero ==
output is buffered and sent in blocks of that size, ie. 0xFFFF for 64k; default is buffered to 64kb (max)
void fflush(); //force output from buffer (flush output buffer)
void exit([string MSG]); //abort script execution and exit process; before exit print MSG if
provided
void quit([string MSG]); //abort script execution but persistent process remains active
uint uptime(); //number of seconds process is active
uint requests(); //number of requests (scripts) process has executed ie. 1, 2, 50, 5000
uint rss(); //process resident set size (memory footprint), in kilobytes
uint rand(); //random unsigned integer number
uint time(); //current time, in seconds; number of seconds since epoch time
uint microtime(); //current time in microseconds
string localdate([uint SECONDS]); //local date string, if no args date is for current time, identical to
calling Server.localdate(Server.time())
string gmtdate([uint SECONDS]); //GMT date
uint getpid(); //process PID no
string getcwd(); //get current working dir
//system error functions
uint errno([uint ERRNO]); //system errno. With no argument, get system error number. If argument is
provided and value 0, sets errno to zero
string errstr([uint ERRNO]); //system error string. If ERRNO supplied, string for that specific ERRNO
string errnstr([uint ERRNO]); //returns string with joined errno() and errstr(). If ERRNO supplied,
string for that specific ERRNO

string array dirlist(string DIRPATH); //list filenames in DIRPATH and return as array of strings, without "."
and ".." entries
string filemodestring(uint MODE); //ie. for mode 0755 return string -rwxr-xr-x

object Environ environ(); //function "Server.environ()" returns JS Object with all environment
variables as object's properties (see example below)
string getenv(string VARNAME); //returns specific env variable

array argv(); //returns array of command line arguments




/*All functions below return true if operation succeeded, false
otherwise; If operation failed, Server.errno() will give the system
error number:*/
bool chdir(string DIRPATH); //change working dir to DIRPATH
bool mkdir(string DIRPATH, uint MODE); //make new dir under filemode MODE
bool rmdir(string DIRPATH); //remove empty dir
bool chmod(string PATH, uint MODE); //change mode of PATH to MODE
bool rename(string OLDPATH, string NEWPATH); //rename/move OLDPATH to NEWPATH
bool move(string OLDPATH, string NEWPATH); //alias for rename
bool symlink(string EXISTINGPATH, string NEWLINKPATH); //create a symlink
bool link(string EXISTINGPATH, string NEWLINKPATH); //create a hard link
bool unlink(string PATH); //remove a file
bool copy(string FILEPATH, string NEWFILE [, bool APPEND]); //copy FILEPATH file to NEWFILE, if third
arg APPEND present and non-zero then append to destination
//
string readlink(string PATH); //read the contents of the symbolic link
path in PATH and return as string. On error returns null.

//file status
object Stat stat(string PATH [, bool INFOABOUTSYMLINK]); //get file status; null returned on error


//utility
uint hash(string TEXT); //create unique uint for string TEXT
string execve(string PATHTOEXE); //run executable on location PATHTOEXE and return it's output as a string; if
execve failed or proces unclean exit server errno is non-zero
uint ip2n(string IPADR); //IPv4, for string "123.45.67.8" return numeric value 23478899
string n2ip(uint IPNUM); //IPv4, for numeric value 23478899 return string "123.45.67.8"
object Hostent gethostby(string NAMEORADR [, string GETHOSTBY]); //IPv4, first arg is name or IP addr; second arg
GETHOSTBY is keyword "name" or "address" indicating lookup by name or IP address; if omitted lookup is by name



//string-chars manipulation functions
string chartrim(string DATA, string CHARS2TRIM, uint WHICHEND);
//trim chars CHARS2TRIM, WHICHEND 1=leading, 2=trailing, 3=trim both ends
//var trimmed = Server.chartrim(" abc ", "\t\r\n ", 3);
//returns string "abc".

string charkeep(string DATA, string CHARS2KEEP);
//keep chars CHARS2KEEP remove all other
//var cleared = Server.charkeep(" abc ", "ac");
//returns string "ac", all other chars removed.

string charremove(string DATA, string CHARSREMOV);
//remove chars CHARSREMOV
//var cleared = Server.charremove(" abc ", " c");
//returns string "ab", spaces and c removed.

string charreplace(string DATA, string CHARSFROM, string CHARSTO);
//char by char replace, CHARSFROM change to CHARSTO
//var changed = Server.charreplace(" abc ", " b", "_");
//returns string "_a_c_", spaces and b changed to _.

string charcutto1(string DATA, string WHICH);
//cut repetitive successive chars to 1 count
//var ccut = Server.charcutto1(" aaa bbbb ccc ", " a");
//returns string " a bbbb ccc ", with a and spaces reduced to 1 count.
};


//example:
//print localdate
printf(Server.localdate(), "<br>");

//file copy example:
if ( Server.copy("myfile.txt", "myfile2.txt")==true ) {
//operation succeded
}










ENVIRON OBJECT:
--------------------------------------------------------------------------------
The "Environ" object includes a collection of environment variables.

//object
var environobj = Server.environ();
//environment variables:
environobj.REQUEST_METHOD or environobj["REQUEST_METHOD"]
environobj.CONTENT_LENGTH or environobj["CONTENT_LENGTH"]
environobj.QUERY_STRING
.... etc etc.

//example:
//print all environment variables ie.:
//REQUEST_METHOD = POST<br>
//CONTENT_LENGTH = 123<br>
for ( key in environobj ) {
printf(key, " = ", environobj[key], "<br>");
}

//get a single env variable:
var contlen = Server.getenv("CONTENT_LENGTH");










STAT OBJECT:
--------------------------------------------------------------------------------
The "Stat" object provides file status information.
//prototype:
object Stat {
//properties:
uint size; //size of file in bytes
uint ta; //time of last access, in seconds
uint tm; //time of last modified
uint tc; //time of last file status change
uint mode; //file mode, ie. 0644

//bools indicating file type
bool isreg; //true if regular file
bool isdir; //true if file is a directory
bool islink; //true if symlink
bool ischar; //true if char special
bool isblock; //true if block special
bool isfifo; //true if named pipe (fifo)
bool issock; //true if socket
};

//example:
var statobj = Server.stat(string PATH [, bool SYMLINKINFO]); //prototype
var statobj = Server.stat("/path/to/myfile.txt"); //get file status information
var statobj = Server.stat("/path/to/myfile.txt", 1); //same, if file is symlink get information about link itself not
file it points to
//ok
if ( statobj!=null ) {
printf("The size of myfile.txt is ", statobj.size, "<br>");

if ( statobj.isreg ) {
//regular file
}
if ( statobj.isdir ) {
//directory
}
}
//error
else {
printf("ERROR: Getting information about myfile.txt failed<br\n>");
printf("system errno [", Server.errno(), "] ", Server.errstr(),"<br\n>");
}






HOSTENT OBJECT:
--------------------------------------------------------------------------------
//prototype:
object Hostent {
string name; //official name of host
array aliases ; //string array alias list
array addresses; //string array list of addresses from name server
uint error; //herror (host error) number; 0 if gethostby succedded
};

//example:
var Exmplhostent = Server.gethostby("123.34.67.89", "adr");
if ( Exmplhostent.error==0 ) {
//operation succeded
printf(Exmplhostent.name, "<br>"); //print official name of host
printf(Exmplhostent.aliases.join(", "), "<br>"); //print joined array of aliases
printf(Exmplhostent.addresses.join(", "), "<br>"); //print joined array of adresses
}










SESSION OBJECT:
--------------------------------------------------------------------------------
Built-in "Session" object provides methods for efficiently reading/storing
variables between script executions.
Session variables are disk based (stored on disk) and have no direct memory
limitation ie. it is ok using a 20mb data in session variable if required.
Variables are stored as text, meaning that numbers (or objects) must first be
converted to string and then stored in session variable.
When reading a numeric (or object) value from session variable, it is a reverse
process, value is retrieved as text, then converted to it's original type.
Each session is unique and defined by identifier sent to HTTP client/browser as
session-id cookie.

//prototype:
object Session {
//methods:
uint time([uint DURATION]); //get or set duration of variables in seconds; used with no argument returns the
duration of session variables, otherwise argument sets session duration; setting time to 0 has effect of deleting all variables
string get(string NAME); //get value of variable NAME; if variable is not available an empty string is
returned
void set(string NAME, string VALUE); //for variable NAME set value to VALUE; setting an empty string "" for VALUE has
effect of deleting a value
void todisk(); //optional, store session to disk (normally done at end of script execution)
};
//example:
var sesdurat = Session.time(); //get current duration of session variables
Session.time(5*60); //set duration to 5 minutes; set value is within the limit of max allowed duration
defined in Bauk configuration script
var mysesvar = Session.get("mysesvar"); //get value of mysesvar
Session.set("othervar", "xyz"); //set "othervar" to value "xyz"
Session.todisk(); //force storing session on disk and release memory (not wait for end of script
execution)
var othervar = Session.get("othervar"); //ok to call again after storing on disk
Session.time(10*60); //change duration
Session.set("anothervar", "abc"); //set "anothervar" to value "abc"
Session.todisk(); //again, to disk
//..etc etc...

/*
Note: all session methods are "safe" which means that all methods can be used
any number of times and in any desired sequence. Ie. it is ok to call get(),
set(), time(), todisk(), then again get(), set(), time() todisk() etc. and the
final result is always same (session is always eventually stored to disk at end
of script execution)
*/










FILE CLASS:
--------------------------------------------------------------------------------
Built-in "File" class provides access to files for read/write, and additional
functions for manipulating file data such as lock, truncate, seek, etc.
File data access is in block (chunk) mode and "textual" (data is first converted
to string then stored), ie. calling function myfile.read(20) reads 20 bytes from
current file position, myfile.write("abcd") writes string "abcd" to file's
current position. When reading numbers, value is retrieved as string and then
converted to numeric value (ie. using parseInt() and parseFloat()).
Additional information about file itself ie. file type, permissions, etc. can be
obtained using Server.stat() function.
//example
var fileobj = new File(string FILEPATH);
var fileobj = new File("/path/to/myfile.txt");

//class
class File {
//methods
bool open(string OPENMODE [,uint CREATEMODE]); //open file by specified mode OPENMODE; see below
bool close(); //close; also removes any lock file has set
int write(string DATA [, string DATA2, ...]); //write to file; multiple arguments; returns number of bytes written;
on error returns -1
string read([uint LEN]); //read LEN bytes and return as JavaScript string; if no argument read
all available bytes from current file position onward; on failure null returned
int cat([uint LEN]); //cat LEN bytes to stdout, if no argument, cat all available bytes
from current file position onward; returns number of bytes done; -1 returned on error
uint tell(); //tell current file position
bool seek([uint ABSPOSITION]); //seek to new absolute position within file, if no argument seek to
end of file
string path(); //returns file path
bool lock(string LOCKTYPE); //lock using LOCKTYPE; see below
bool unlock(); //release lock
bool truncate([uint LEN]); //truncate opened file to new length; if no argument truncate to
current file position
};

Open modes:
r = open for reading
w = open for writing and set file position to beggining of file
c = create file by mode CREATEMODE if not existing
t = truncate file
a = open for write/append and set position to end of file, excludes truncate flag

Lock modes:
s = set shared lock
x = set exclusive lock
n = non-blocking, attempt to set lock but if locked by another process and would block, return error EWOULDBLOCK



//example
var fileobj = new File("/path/to/myfile.txt");
//open for RW, truncate and if not existing create mode 0644
if ( fileobj.open("rwtc", 0644)==true ) {
//set exclusive lock, blocking
if ( fileobj.lock("x")==true ) {
//locked
fileobj.unlock();
}
//set non-blocking exclusive lock
if ( fileobj.lock("xn")==true ) {
//locked
fileobj.unlock();
}
//set shared lock; process blocked untill capable of setting lock
if ( fileobj.lock("s")==true ) {
//locked
fileobj.unlock();
}

fileobj.close();
}
//open and read complete file
if ( fileobj.open("r")==true ) {
var fdata = fileobj.read(); //read all
if ( fdata!=null ) {
//ok
}
fileobj.close();
}










SQLITE CLASS:
--------------------------------------------------------------------------------
Built-in "SQLite" class provides interface for using SQLite3 database.

//constructor
var databaseobj = new SQLite(string DBPATH);
var databaseobj = new SQLite("/path/to/mydatabase.db");

//class
class SQLite {
//methods
bool open(); //open database, returns true if succedded
bool close(); //close database
bool exec(string STATEMENT); //execute a result-less SQL statement
bool query(string SQLQUERY); //execute SQL query SQLQUERY and create result set
string colname(uint INDX); //for column at INDX return column name used in CREATE table statement
string coltype(uint INDX); //for column at INDX return column data type used in CREATE statement ie. INTEGER,
CHAR, FLOAT
uint colcount(); //number of columns in result set
uint rowcount(); //number of rows in result set
bool rowhas(); //returns true if there is row under cursor available
array rowfetch(); //from result set get single row, returned as JavaScript array of strings; null
returned if no row available
array array rowallfetch(); //from result set get all rows, returned as JavaScript two-dimensional array of
strings
uint rowlastinsertid(); //returns id created by database last insert operation
uint lastinsertrowid(); //alias for rowlastinsertid
bool rewind(); //move to first row of result set
string error(); //returns SQLite3 error report string
};



//example:
//BEGIN CODE-->
//demonstrate using SQLite3 database and JavaScript interface
printf("<html><body>");

var dbfilepath = "mydatabase.db";
var databaseobj = new SQLite(dbfilepath);


printf("<b>Opening database.</b><br>");

if ( databaseobj.open()==true ) {
printf("Executing CREATE and INSERT statement.<br>");

//statement
var ssqlstmt = ""
+"CREATE TABLE ttesttable (i INTEGER PRIMARY KEY, cname CHAR(255), cweight INTEGER); "
+"INSERT INTO ttesttable (cname,cweight) VALUES ('firstuser',95); "
+"INSERT INTO ttesttable (cname,cweight) VALUES ('anotheruser',263); "
;

//if statements executed ok...
if ( databaseobj.exec(ssqlstmt)==true ) {
printf("Using SELECT query to fetch inserted values.<br>");
//query
if ( databaseobj.query("SELECT * FROM ttesttable")==true ) {
//printing selected values in tabular form ie.
//colname (TYPE) colname (TYPE) colname (TYPE)
//--------------------------------------------------
//value value value
//value value value
//etc etc...
printf("Printing selected values in tabular form.<br><br>");
printf("<table bgcolor=\"#DDDDDD\" cellspacing=1 cellpadding=4>");

//print header row with column names and types
printf("<tr bgcolor=\"#eeeeee\">");
for ( var ccol=0; ccol!=databaseobj.colcount(); ccol++ ) {
printf("<td><b>");
printf(databaseobj.colname(ccol));
printf(" (");
printf(databaseobj.coltype(ccol));
printf(")</b></td>");
}
printf("</tr>");


//print rows
var nrows = 0;
while ( (onerow=databaseobj.rowfetch())!=null ) {
printf("<tr bgcolor=\"#FFFFFF\">");
for ( var indx in onerow ) {
printf("<td>");
printf(onerow[indx]);
printf("</td>");
}
printf("</tr>");

nrows++;
}

printf("</table>");
printf("<br>");

printf("<i>number of rows in select statement [");
printf(nrows);
printf("]</i><br>");
}
}
//error
else {
//ie. table already exist etc
printf("Error in exec, error [" ,databaseobj.error(), "]<br>");
}

printf("<b>Closing database.</b><br>");
databaseobj.close();
printf("Database closed.<br>");
}
//error
else {
//ie. invalid path, no permission etc
printf("Error opening database, error [" ,databaseobj.error(), "]<br>");
}

printf("Deleting database file.<br>");
//delete database file
if ( Server.unlink(dbfilepath)==true ) {
printf("Database file deleted.<br>");
}
else {
//ie. invalid path, no permission etc
printf("Error deleting file ",dbfilepath,", system errno [" ,Server.errno(), "]<br>");
}

printf("</body></html>");
// <--END CODE










PIPE CLASS:
--------------------------------------------------------------------------------
Built-in "Pipe" class provides interface for using inter-process communication
through Unix pipe, a new process is launched from specified path and
bidirectional pipe is opened for reading/writing to new process.

//constructor
var pipeobj = new Pipe(string EXEPATH);
var pipeobj = new Pipe("/path/to/executable"); //path to executable
var pipeobj = new Pipe("/path/to/executable arg0 arg1 arg2"); //executable with command line arguments

//class
class Pipe {
//methods
bool open(); //open bidirectional pipe, returns true if succedded
uint close([uint WHICHEND]); //close pipe; if argument is supplied, it's either 0=read end close
or 1=write end close; with no argument, closes both ends and returns status 0 for success; status nonzero indicates an error
string read(); //read from pipe untill EOF and return data as a string
int write(string ARG0 [, string ARG1 , ...]); //write to pipe; returns no of bytes written; returns -1 on error
};


//example:
//BEGIN CODE-->
//sending email using Pipe class and sendmail:
printf("<html><body>");
var pipeobj = new Pipe("/usr/sbin/sendmail (e-mail address removed)");

if ( pipeobj.open()==true ) {
var smsg = ""
+"From: (e-mail address removed)\n"
+"To: (e-mail address removed)\n"
+"Subject: Webscript test email\n"
+"\n"
+"Text text text\n"
+"more text some more text etc.\n"
+"\n"
;

//writing ok
if ( pipeobj.write(smsg)!=(-1) ) {
pipeobj.close(1); //close write end
printf("<pre>");
printf(pipeobj.read()); //read and print output, if any
printf("</pre>");
}
//error
else {
printf("Failed writing to pipe [errno " , Server.errno() ,"]<br\n>");
}

var xstatus = pipeobj.close(); //final close completely closes pipe and returns pipe status

//if non-zero there was an error or process unclean exit
if ( xstatus!=0 ) {
printf("Closing pipe indicate failure [exit status " , xstatus ,"]<br\n>");
printf("System status [errno " , Server.errno() ,"]<br\n>");
}

}
else {
printf("Opening pipe failed, system status [errno " , Server.errno() ,"]<br\n>");
}
printf("</body></html>");
// <--END CODE














DICTIONARY CLASS:
--------------------------------------------------------------------------------
Built-in "Dictionary" class is a hash array of unlimited length.
Values are objects of any type and in Dictionary are stored by refference, not
by copy. Optional argument SPEEDLEVEL (0-20) is used to increase the speed of
array read/write by setting the size of Dictionary's hash table.

//constructor
var dictobj = new Dictionary([uint SPEEDLEVEL]); //optional argument SPEEDLEVEL 0-20 is used to increase the size of hash
table

//class
class Dictionary {
//methods
void set(string NAME, object VALUE); //set the value in dictionary; setting new value over-writes previously set
value; if VALUE is null effectively removes previously set value from dictionary
object get(string NAME); //get value from dictionary; null returned if value not in dictionary
uint len(); //number of values stored in dictionary
};

//example:
var dictobj = new Dictionary(5); //create new dictionary
var exmplobj = new Object(); //create new object to store in dictionary
dictobj.set("name123",exmplobj); //store object in dictionary

//now read value from dictionary
var rdobj = dictobj.get("name123");
if ( rdobj!=null ) {
// ...
}








--
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top