JavaScript API Reference

WebSQL Server embeds V8 JavaScript Engine and enhances it with the parallel computing capabilities. JavaScript can be used to process HTTP requests, access databases, write highly-parallel and scalable programs that leverages multicore processors, etc. WebSQL Server creates a pool of JavaScript threads and HTTP requests are likely to be processed in parallel on different JavaScript threads from the pool. The parallelization is based on the the underlying hardware capabilities (more core/processors - more parallelization). Every JavaScript thread has its own V8 instance, but it can share data with other threads via the provided thread-safe API. WebSQL Server provides the following objects and functions in the global scope:


The request global object represents an incoming HTTP request on the current JavaScript thread.

request.isHttps() Indicates whether the HTTP connection uses HTTPS.
request.isGetMethod() Indicates whether the HTTP request uses GET method.
request.isPostMethod() Indicates whether the HTTP request uses POST method.
request.hostname Returns the domain or IP address of the HTTP request.
request.pathname Returns the path of the HTTP request.
request.query("name") Returns a query string value of the HTTP request.
request.header("name") Returns a header value of the HTTP request.
request.cookie("name") Returns a cookie value of the HTTP request.
request.form["name"] Returns an HTML form value of the HTTP request body.
request.body.json() Generates a JavaScript object from the HTTP request body.

The response global object represents the response for an incoming HTTP request on the current JavaScript thread.

response.cookie = "cookie string" Adds a new cookie to the HTTP response.
response.header("name", "value") Adds a new header to the HTTP response.
response.write("data") Appends the data to the HTTP response body.
response.end()
response.end(statusCode)
response.end(statusCode, "status text")
response.end(303, "RedirectURL")
response.end("/RelativeFilePath.html")
response.end(error)
response.end(error, statusCode)
response.end(error, statusCode, "status text")
Send the HTTP response.

The session global object represents the session of an incoming HTTP request on the current JavaScript thread.

session.exists() Indicates whether the HTTP request has a cookie representing a session and the session object exists on the server.
session.create() Generates a random string with the BCryptGenRandom function, adds it to the HTTP response cookies, and creates a session object on the server.
session.remove() Delete the cookie and the session object.
session.set("name", "value") Store the value on the server in the session object of the current HTTP request. Note (thread-safe): the value is shared between JavaScript threads which access the same session.
session.get("name") Returns a session value of the current session object. Note (thread-safe): the value can be set on a different JavaScript thread in parallel.

Example:

(function() {
    if (!session.exists()) {
        session.create();
        response.cookie = "additionalCookie=123; Path=/; Secure";
    }
    var param = request.cookie("name");
    session.set("name", param);
    response.write("something");
    response.end();
}());
        

The db global function provides a SQL-like interface (WebSQL) to access both Relational and NoSQL databases.

db("select|insert|update|replace|delete ...", function(data) {...})
db("insert|update|replace ...", object, function(data) {...})
db("name", "select|insert|update|replace|delete ...", function(data) {...})
db("name", "insert|update|replace ...", object, function(data) {...})
Executes the specified WebSQL asynchronously.
name: specifies a configured database connection, otherwise a default configured database connection.
See Database connections.
data.forEach(function(item) {...}) Iterates through selected data or throws an exception in case of an error.
data.throwIfError() Throws an exception in case of an error.

Example:

(function() {
    var json = request.body.json();
    json.Something = session.get("name");
    db("insert into aTable", json, function(data) {
        try {
            data.throwIfError();
            response.end();
        } catch (err) {
            response.end(err);
        }
    });
}());
        
(function() {
    var param = request.query("name");
    db("select * from aTable where Something = '" + param + "'", function(data) {
        try {
            var json = "{\"Items\":[0";
            data.forEach(function(item) {
                json += ",";
                json += item.Something;
            });
            json += "]}";
            response.write(json);
            response.end();
        } catch (err) {
            response.end(err);
        }
    });
}());
        

The net global function allows to access other servers via HTTP. See also the signature example.

net("method", "URL", function(resp) {...})
net("method", "URL", headers, function(resp) {...})
net("method", "URL", headers, "body", function(resp) {...})
net("method", "URL", headers, "body", signature, function(resp) {...})
Send the specified HTTP request asynchronously.
resp Represents the HTTP response with the interface standardized in the W3C.

Example:

(function() {
    var url = "http://example.com/something?param=123";
    var headers = {
        Content-Type: "text/plain"
    };  
    net("POST", url, headers, "data", function(resp) {
        try {
            if (resp.status == 200) {
                response.write(resp.responseText);
            } 
            response.end(resp.status);
        } catch (err) {
            response.end(err);
        }
    });
}());
        

The email global object allows to send emails via configured drivers.

var msg = new email() Creates a new email envelope.
msg.to Specifies the address of the receiver.
msg.from Specifies the address of the sender.
msg.subject Specifies the subject of the message.
msg.body Specifies the content of the message.
msg.send() Sends the email.

The console global object represents a browser's debugging console. If the console is not registered, it does nothing. See also Remote Console.

console.log("text") Outputs a message to the console.

The log global function writes messages into a server-side log. The server-side log is accessible via the Web-based IDE.

log("text") Writes a message into the server-side log.

The following global functions provide access to cryptographic services:

cryptoRandomStringBase64(numberOfBytes) Generates random bytes with the BCryptGenRandom function and returns them as a base64 string.
cryptoRandomStringHex(numberOfBytes) Generates random bytes with the BCryptGenRandom function and returns them as a hex string.
cryptoHashStringBase64("text") Generates a hash and returns it as a base64 string.
cryptoHashStringHex("text") Generates a hash and returns it as a hex string.
cryptoKeyHashStringBase64("text", "salt") Generates a keyed hash (HMAC) with the salt and returns it as a base64 string.
cryptoKeyHashStringHex("text", "salt") Generates a keyed hash (HMAC) with the salt and returns it as a hex string.
encryptStringBase64("text") Encrypts the text with an encryption key from the settings and returns it as a base64 string.
encryptStringHex("text") Encrypts the text with an encryption key from the settings and returns it as a hex string.
decryptStringBase64("text") Decrypts the base64 text with an encryption key from the settings and returns it as a string.
decryptStringHex("text") Decrypts the hex text with an encryption key from the settings and returns it as a string.

The fork and join global function enables executing JavaScript in parallel and merging results. See Concurrent, Parallel, Distributed. See also MapReduce.

fork("/RelativeFilePath.js")
fork("/RelativeFilePath.js", args1, ...)
fork(delayMilliseconds, "/RelativeFilePath.js")
fork(delayMilliseconds, "/RelativeFilePath.js", ...)
Schedules the JavaScript to be executed on the thread pool (in parallel on a different JavaScript thread). The arguments are accessible via the array-like $args global object.
$args[index] Returns an argument passed to a parallel JavaScript. The first argument starts at 0.
var mtx = mutex() Creates a mutex queue for the join function.
join(mtx, function(state) {...})) Schedules the callback function to be executed exclusively on the mutex.
state.counter Represents the number of executed functions on the mutex so far (including the currently executing function).
state.data Represents data associated with the mutex. The currently executing function has an exclusive access to the data.

See Also:

Table of Contents