Request

Moduleejs.web
Definitiondynamic class Request
InheritanceRequest inherit Object
Specifiedejscript-2.5
StabilityPrototype 8.

Web request class.

Request objects manage the state and execution of a web request. The HttpServer class creates instances of Request in response to incoming client requests. The Request object holds the client request state including the request URL and headers. It provides low-level properties and methods to inspect and control the request. The Request object is a Stream and by calling the read() and write() methods, request body content can be read and written.

The response to send back to the client can be defined by setting status and calling setHeaders() and write() to set the response status, headers and body content respectively.


Properties

QualifiersPropertyTypeDescription
static const SecurityTokenName Security Token for use to help mitigate CSRF security threats.
absHomeUriUri for the top-level of the application. This is an absolute Uri that includes scheme and host components. See home to get a relative Uri.
get set asyncBooleanThe current async mode.Request does not support sync mode and only supports async mode. Set to true if the stream is in async mode.
authGroupStringAuthentication group. This property is set to the value of the authentication group header. This field is read-only.
authTypeStringAuthentication method if authorization is being used (basic or digest). Set to null if not using authentication. This field is read-only. 0.
authUserStringAuthentication user name. This property is set to the value of the authentication user header. Set to null if not yet defined. This field is read-only.
autoFinalizingBooleanControl whether auto-finalizing will be used for the request. If autoFinalizing is false, a request must call finalize() to signal the end of write data. If autoFinalize is true, the Request class will automatically call finalize at the conclusion of the request. Applications that wish to keep the request open to the client can suppress auto-finalization by setting autoFinalizing to false or by calling dontAutoFinalize(). This property defaults to true.
configObjectRequest configuration. Initially refers to App.config which is filled with the aggregated "ejsrc" content. Middleware may modify to refer to a request local configuration object.
contentLengthNumberGet the request content length. This is the length of body data sent by the client with the request. This property is read-only and is set to the length of the request content body in bytes or -1 if not known. Body data is readable by using read() or by using the request object as a stream.
contentTypeStringThe request content type as specified by the "Content-Type" Http request header. This is set to null if not defined. This is the content type of the request body content sent with the request.
controllerControllerAssociated Controller object. Set to null if no associated controller. 8.
cookiesObjectCookie headers. Cookies are sent by the client browser via the Set-Cookie Http header. They are typically used used to specify the session state. If sessions are being used, an Ejscript session cookie will be sent to and from the browser with each request.
dirPathApplication web document directory on the local file system. This is set to the directory containing the application. For MVC applications, this is set to the base directory of the application. For non-MVC apps, it is set to the document root directory specified when the HttpServer was instantiated.
envObjectStorage for middleware specific state. Added for JSGI compliance.
errorMessageStringDescriptive error message for the request. This message is defined internally by the Request if a request times out or has a communications error. 8.
get extensionStringThe request pathInfo file extension.
filenamePathPhysical filename for the resource supplying the response content for the request. Virtual requests where the Request uri does not correspond to any physical resource may not define this property.
filesObjectFiles uploaded as part of the request. For each uploaded file, an instance of UploadFile is created in files. Each element is named by the file upload HTML input element ID in the HTML page form.
get finalizedBooleanHas the request output been finalized.
headersObjectRequest Http headers. This is an object hash filled with lower-case request headers from the client. If multiple headers of the same key value are defined, their contents will be catenated with a ", " separator as per the HTTP/1.1 specification. Use the header() method if you want to retrieve a single header. Headers defined on the server-side by creating new header entries in headers will preserve case. Use header() if you want to match headers using a mixed case key. e.g. header("Content-Length").
homeUriHome URI for the application. This is a relative Uri from the current URI to the the top-most directory level of the application.
hostStringHost serving the request. This is initialized to the authorized server hostname (HttpServer.name) if one is configured. Otherwise it will use Http "Host" header value if supplied by the client else the server IP address of the accepting interface. This algorithm attempts to use the most public address available for the server.
flashObjectNotification "flash" messages to pass to the next request (only). By convention, the following keys are used. error: Negative errors (Warnings and errors), inform: Informational / postitive feedback (note), warn: Negative feedback (Warnings and errors), *:: Other feedback (reminders, suggestions...).
isSecureBooleanFlag indicating if the request is using secure communications. This means that TLS/SSL is the underlying protocol scheme.
formDataStringThe request form parameters as a string. This parameters are www-url decoded from the POST request body data. This is useful to get a stable, sorted string representing the form parameters.
limitsObjectResource limits for the request. The limits have initial default values defined by the owning HttpServer.
localAddressStringServer IP address of the accepting interface.
get inputStreamRequest content stream. This is equivalent to using "this" as Request objects are streams connected to the input content. Added for JSGI compliance.
static jsgiObjectJSGI specification configuration object.
logLoggerLogger object. Set to App.log. This is configured from the "log" section of the "ejsrc" config file.
methodStringRequest HTTP method. String containing the Http method (DELETE | GET | POST | PUT | OPTIONS | TRACE).
originalMethodStringOriginal HTTP request method used by the client. If the method is overridden by including a "-ejs-method-" parameter in a POST request or by defining an X-HTTP-METHOD-OVERRIDE Http header, the original method used by the client is stored in this property and the method property reflects the newly defined value. If method is not overridden, originalMethod will be null.
originalUriUriThe original request URI supplied by the client. This is the Uri path supplied by the client on the first line of the Http request. It is combined with the HttpServer scheme, host and port components to yield a fully qualified URI. The "uri" property has fields for: scheme, host, port, path, query and reference. The "uri" property is read-only. 0.
paramsObjectThe request form parameters plus other routing parameters. The form parameters are www-url decoded from the POST request body data. See also form.
referenceStringRequest reference string. This is the portion of the Uri after the "#". Set to null if there is no reference.
referrerStringName of the referring URL. This comes from the request "Referrer" Http header. Set to null if there is no defined referrer. Note: the HTTP header is misspelt as "referer" 0.
remoteAddressStringIP address of the client issuing the request. 8.
respondedBooleanThe application has responded in some way. The application has commenced a response by doing some output or setting status.
responseHeadersObjectHttp response headers. This is the proposed set of headers to send with the response. The case of header keys is preserved.
pathInfoStringLocation of the request within the application. This is the portion of the request URL after the scriptName. The pathInfo is originally derrived from uri.path after splitting off the scriptName. Changes to the uri or scriptName properties will not affect the pathInfo property.
routeRouteRoute used for the request. The route is the matching entry in the route table for the request. The route has properties two properties of particular interest: "name" which is the name of the route and and "type" which classifies the type of request.
schemeStringHttp request scheme (http | https).
scriptNameStringScript name for the current application serving the request. This is typically the leading Uri portion corresponding to the application, but middleware may modify this to be an arbitrary string representing the application. The script name is often determined by the Router as it parses the request using the routing tables. The scriptName will be set to the empty string if not defined, otherwise is should begin with a "/" character. NOTE: changing script name will not update the home property.
serverHttpServerOwning server for the request. This is the HttpServer object that created this request.
portNumberTCP/IP port number for the server of this request.
protocolStringHttp request protocol (HTTP/1.0 | HTTP/1.1).
queryStringRequest query string. This is the portion of the Uri after the "?". Set to null if there is no query.
get queryStringStringDecoded query string (URL query string). Eqivalent to the query property. Added for JSGI compliance.
get securityTokenObjectGet a security token to help mitigate CSRF threats. The security token is submitted by forms and requests and can be validated by controllers. The token is stored in session["__ejs-security-token__"].
get serverPortNumberListening port number for the server.
sessionSessionSession state object. The session state object can be used to share state between requests. If a session has not already been created, accessing this property automatically creates a new session and sets the Request.sessionID property and a cookie containing a session ID sent to the client with the response. To test if a session has been created, test the sessionID property which will not auto-create a session. Objects are stored in the session state using JSON serialization.
sessionIDStringCurrent session ID. Index into the sessions object. Set to null if no session is defined.
statusNumberSet to the (proposed) Http response status code.
uriUriThe current request URI. This property is read-only and is dynamically computed from the originalUri combined with the current scheme, host, port, scriptName, pathInfo, query and reference property values. The "uri" property has fields for: scheme, host, port, path, query and reference.
writeBufferByteArrayWrite buffer when capturing output.
get writtenNumberThe number of bytes written to the client. This is the count of bytes passed to write and buffered, not the actual number of bytes sent to the network connection.

Request Class Methods

(No own class methods defined)

QualifiersMethod

Request Instance Methods

QualifiersMethod
Request(uri: Uri, dir: Path = .)
 Construct the a Request object.
autoFinalize(): Void
 Finalize the request if autoFinalizing is true.
checkSecurityToken()
 Check the request security token.
close(): Void
 Close the stream.This closes the current request by finalizing all transmission data and sending a "close" event.
createSession(timeout: Number = -1): Session
 Create a session state object.
destroySession(): Void
 Destroy a session.
dontAutoFinalize(): Void
 Stop auto-finalizing the request.
error(msg: String): Void
 Set an error flash notification message.
finalize(): Void
 Signals the end of any and all response data and flushes any buffered write data to the client.
finalizeFlash()
 Save flash messages for the next request and delete old flash messages.
flush(dir: Number = expression): Void
 Flush the stream and underlying streams.Flush request data.
header(key: String): String
 Get a request header by keyword.
inform(msg: String): Void
 Set an informational flash notification message.
link(target: Object): Uri
 Create a URI link.
matchContent(formats: Array): String
 Select the response content type based on the request "Accept" header.
notify(key: String, msg: String): Void
 Set a transient flash notification message.
off(name, observer: Function): Void
 Remove an observer from the stream.
on(name, observer: Function): Request
 Add an observer to the stream for the named events.
read(buffer: ByteArray, offset: Number = 0, count: Number = -1): Number
 Read a data from the stream.If the request is posting a form, i.e.
redirect(target: Object, status: Number = expression): Void
 Redirect the client to a new URL.
setCookie(name: String, options: Object)
 Define a cookie header to send with the response.
setHeader(key: String, value: String, overwrite: Boolean = true): Void
 Convenience routine to set a Http response header in responseHeaders.
setHeaders(headers: Object, overwrite: Boolean = true): Void
 Convenience routine to set multiple Http response headers in responseHeaders.
setLimits(limits: Object): Void
 Update the request resource limits.
setLocation(prefix: String, location: Path): Void
 Convenience routine to define an application at a given Uri prefix and directory location.
setStatus(status: Number): Void
 Convenience routine to set the (proposed) Http response status code.
setupFlash()
 Prepare the flash message area.
trace(options: Object): Void
 Configure request tracing for the request.
warn(msg: String): Void
 Set a warning flash notification.
write(data: Array): Number
 Write data to the stream.Write data to the client.
writeError(status: Number, msgs: Array): Void
 Write an error message back to the user and finalize the request.
writeFile(file: Path): Boolean
 Send a static file back to the client.
writeResponse(response: Object): Void
 Send a response to the client.
writeSafe(data: Array): Number
 Write safely.

Method Detail

ejs.web Request(uri: Uri, dir: Path = .)
Description
Construct the a Request object. Request objects are typically created by HttpServers and not constructed manually.
Parameters
uri: Uri Request URI.
dir: Path Default directory containing web documents. [default: .]

autoFinalize(): Void
Description
Finalize the request if autoFinalizing is true. Finalization signals the end of any write data and flushes any buffered write data to the client. This routine is used by frameworks to finalize requests if required.

checkSecurityToken()
Description
Check the request security token. If a required security token is defined in the session state, the request must supply the same token with all POST requests. This helps mitigate potential CSRF threats.
Throws

close(): Void
Description
Close the stream.This closes the current request by finalizing all transmission data and sending a "close" event. HttpServer attemps to reuse socket connections so calling close(), may not actually close the socket connection if the reuse limit has not been exceeded (see limits). It is normally not necessary to explicitly call close a request as the web framework will automatically close finalized requests when all input data has fully been read. Calling close on an already closed request is silently ignored.
Events
closeA close event is issued before closing the stream.

createSession(timeout: Number = -1): Session
Description
Create a session state object. The session state object can be used to share state between requests. If a session has not already been created, this call will create a new session and initialize the session property with the new session. It will also set the sessionID property and a cookie containing a session ID that will be sent to the client with the response. Sessions can also be used/created by simply accessing the session property. Objects are stored in the session state using JSON serialization.
Parameters
timeout: Number Optional session state timeout in seconds. Set to zero for no timeout. After the timeout has expired, the session will be deleted. [default: -1]

destroySession(): Void
Description
Destroy a session. This call destroys the session state store that is being used for the current client. If no session exists, this call has no effect. Sessions are created by reading or writing to the session property. 0.

dontAutoFinalize(): Void
Description
Stop auto-finalizing the request. This will set autoFinalizing to false. Some web frameworks will "auto-finalize" requests by calling finalize() automatically at the conclusion of the request. Applications that wish to keep the connection open to the client can defeat this auto-finalization by calling dontAutoFinalize().

error(msg: String): Void
Description
Set an error flash notification message. Flash messages persist for only one request and are a convenient way to pass state information or feedback messages to the next request. To use flash messages, setupFlash() and finalizeFlash() must be called before and after the request is processed. HttpServer.process will call setupFlash and finalizeFlash automatically.
Parameters
msg: String Message to store.

finalize(): Void
Description
Signals the end of any and all response data and flushes any buffered write data to the client. If the request has already been finalized, this call has no additional effect.

finalizeFlash()
Description
Save flash messages for the next request and delete old flash messages. (.

flush(dir: Number = expression): Void
Description
Flush the stream and underlying streams.Flush request data. A supplied flush direction argument modifies the effect of this call. If direction is set to Stream.READ, then all read data is discarded. If direction is set to Stream.WRITE, any buffered data is written. Stream.BOTH will cause both directions to be flushed. If the stream is in sync mode, this call will block until all data is written. If the stream is in async mode, it will attempt to write all data but will return immediately. Defaults to Stream.WRITE.Calling flush(Sream.WRITE) or finalize() is required to ensure buffered write data is sent to the client. Flushing the read direction is ignored.
Parameters
dir: Number Direction to flush. Set to READ WRITE or BOTH. [default: expression]

header(key: String): String
Description
Get a request header by keyword. Headers supplied by the remote client are stored in lower-case. Headers defined on the server-side preserve case. This routine supports both by doing a case-insensitive lookup.
Parameters
key: String Header key value to retrieve. The key match is case insensitive.
Returns
The header value.

inform(msg: String): Void
Description
Set an informational flash notification message. Flash messages persist for only one request and are a convenient way to pass state information or feedback messages to the next request. To use flash messages, setupFlash() and finalizeFlash() must be called before and after the request is processed. HttpServer.process will call setupFlash and finalizeFlash automatically.
Parameters
msg: String Message to store.

link(target: Object): Uri
Description
Create a URI link. The target parameter may contain partial or complete URI information. The missing parts are supplied using the current request and route tables. The resulting URI is a normalized, server-local URI (begins with "/"). The URI will include any defined scriptName, but will not include scheme, host or port components.
Parameters
target: Object The URI target. The target parameter can be a URI string or object hash of components. If the target is a string, it is may contain an absolute or relative URI. If the target has an absolute URI path, that path is used unmodified. If the target is a relative URI, it is appended to the current request URI path. The target can also be an object hash of URI components: scheme, host, port, path, reference and query. If these component properties are supplied, these will be combined to create a URI. The URI will be created according to the route URI template. The template may be explicitly specified via a "route" target property. Otherwise, if an "action" property is specified, the route of the same name will be used. If these don't result in a usable route, the "default" route will be used. See the Router for more details. If the target is a string that begins with " @" it will be interpreted as a controller/action pair of the form " @Controller/action". If the "controller/" portion is absent, the current controller is used. If the action component is missing, the "index" action is used. A bare " @" refers to the "index" action of the current controller. Lastly, the target object hash may contain an override "uri" property. If specified, the value of the "uri" property will be returned and all other properties will be ignored.
Options
schemeString URI scheme portion.
hostString URI host portion.
portNumber URI port number.
pathString URI path portion.
referenceString URI path reference. Does not include "#".
queryString URI query parameters. Does not include "?".
controllerString Controller name if using a Controller-based route. This can also be specified via the action option.
actionString Action to invoke. This can be a URI string or a Controller action of the form.
routeString Route name to use for the URI template.
Returns
A normalized, server-local Uri object. The returned URI will be an absolute URI.
Example
Given a current request of http://example.com/samples/demo" and "r" == the current request:

r.link("images/splash.png")                  # "/samples/images/splash.png"
r.link("images/splash.png").complete(r.uri)  # "http://example.com/samples/images/splash.png"
r.link("images/splash.png").relative(r.uri)  # "images/splash.png"

r.link("http://example.com/index.html")
r.link("/path/to/index.html")
r.link("\@Controller/checkout")
r.link("\@Controller/")
r.link("\@checkout")
r.link("\@")
r.link({action: "checkout")
r.link({action: "logout", controller: "Admin")
r.link({action: "Admin/logout")
r.link({action: "\@Admin/logout")
r.link({uri: "http://example.com/checkout"})
r.link({route: "default", action: "\@checkout")
r.link({product: "candy", quantity: "10", template: "/cart/{product}/{quantity}}")

matchContent(formats: Array): String
Description
Select the response content type based on the request "Accept" header. See RFC-2616.
Parameters
formats: Array Array of server supported mime types.
Returns
Formats The selected mime types mime type string Accept: "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png".

notify(key: String, msg: String): Void
Description
Set a transient flash notification message. Flash messages persist for only one request and are a convenient way to pass state information or feedback messages to the next request. To use flash messages, setupFlash() and finalizeFlash() must be called before and after the request is processed. HttpServer.process will call setupFlash and finalizeFlash automatically.
Parameters
key: String Flash message key.
msg: String Message to store.

off(name, observer: Function): Void
Description
Remove an observer from the stream.
Parameters
name Event name previously used with observe. The name may be an array of events.
observer: Function Observer function previously used with observe.

on(name, observer: Function): Request
Description
Add an observer to the stream for the named events.
Parameters
name: [String|Array]Name of the event to listen for. The name may be an array of events.
observer: Function Callback observer function. The function is called with the following signature: function observer(event: String, ...args): Void.
Events
readableIssued when the stream becomes readable.
writableIssued when the stream becomes writable.
closeIssued when stream is being closed. 8.
writableIssued when the connection is writable to accept body data (PUT, POST).
closeIssued when the request completes.
errorIssued if the request does not complete or the connection disconnects. An error event is not caused by non-200 status codes, these are regarded as valid return results. Rather, an error event will be issued when the request cannot return a complete, valid Http response to the client. All events are called with the signature: function (event: String, http: Http): Void.

read(buffer: ByteArray, offset: Number = 0, count: Number = -1): Number
Description
Read a data from the stream.If the request is posting a form, i.e. If data is available, the call will return immediately. If no data is available and the stream is in sync mode, the call will block until data is available. If no data is available and the stream is in async mode, the call will not block and will return immediately. In this case a "readable" event will be issued when data is available for reading.the Http ContentType header is set to "application/x-www-form-urlencoded", then the request object will not be created by the HttpServer until all the form data is read and the params collection created and populated with the form data. This permits form data to be processed synchronously without having to use async/observer techniques to respond to readable events. With all other content types, the Request object will be created and run before the incoming client data has been read. To read data in these situations, register an observer function to run when the connection becomes "readable".
Parameters
buffer: ByteArray Destination byte array for read data.
offset: Number Offset in the byte array to place the data. If the offset is -1, then data is appended to the buffer write position which is then updated. If offset is >= 0, the data is read to the offset and the read pointer is set to the offset and the write pointer to one past the end of the data just read. [default: 0]
count: Number Read up to this number of bytes. If -1, read as much as the buffer will hold up. If the stream is of fixed and known length (such as a file) and the buffer is of sufficient size or is growable, read the entire stream. If the buffer is of a fixed size, ready only what will fit into the buffer. [default: -1]
Events
readableIssued when there is new read data available.
writableIssued when the stream becomes empty. `.
Returns
A count of the bytes actually read. Returns null on EOF or errors.
Example
request.on("readable", function(event, request) {
    var data = new byteArray
    if (read(data)) {
        print("Got " + data)
    } else {
        //  End of input, call finalize() when all output has been written
        request.finalize()
    }
})

redirect(target: Object, status: Number = expression): Void
Description
Redirect the client to a new URL. This call redirects the client's browser to a new target specified by the url. Optionally, a redirection code may be provided. Normally this code is set to be the HTTP code 302 which means a temporary redirect. A 301, permanent redirect code may be explicitly set.
Parameters
target: Object Uri to redirect the client toward. This can be a relative or absolute string URI or it can be a hash of URI components. For example, the following are valid inputs: ../index.ejs, http://www.example.com/home.html, @list.
status: Number Optional HTTP redirection status. [default: expression]

setCookie(name: String, options: Object)
Description
Define a cookie header to send with the response. The Path, domain and expires properties can be set to null for default values.
Parameters
name: String Cookie name.
options: Object Cookie field options.
Options
valueCookie value.
pathUri path to which the cookie applies.
domainString Domain in which the cookie applies. Must have 2-3 "." and begin with a leading ".". For example: domain: .example.com.
expiresDate When the cookie expires.
secureBoolean Set to true if the cookie only applies for SSL based connections.

setHeader(key: String, value: String, overwrite: Boolean = true): Void
Description
Convenience routine to set a Http response header in responseHeaders. If a header has already been defined and overwrite is true, the header will be overwritten. NOTE: case is ignored in the header keyword. Access responseHeaders to inspect the proposed response header set.
Parameters
key: String The header keyword for the request, e.g. "accept".
value: String The value to associate with the header, e.g. "yes".
overwrite: Boolean If the header is already defined and overwrite is true, then the new value will overwrite the old. If overwrite is false, the new value will be catenated to the old value with a ", " separator. [default: true]

setHeaders(headers: Object, overwrite: Boolean = true): Void
Description
Convenience routine to set multiple Http response headers in responseHeaders. Access responseHeaders to inspect the proposed response header set.
Parameters
headers: Object Set of headers to use.
overwrite: Boolean If the header is already defined and overwrite is true, then the new value will overwrite the old. If overwrite is false, the new value will be catenated to the old value with a ", " separator. [default: true]

setLimits(limits: Object): Void
Description
Update the request resource limits. The supplied limit fields are updated. See the limits property for limit field details.
Parameters
limits: Object Object hash of limit fields and values.
See Also
limits

setLocation(prefix: String, location: Path): Void
Description
Convenience routine to define an application at a given Uri prefix and directory location. This is typically called from routing tables. This sets the pathInfo scriptName and dir properties.
Parameters
prefix: String The leading Uri prefix for the application. This prefix is removed from the pathInfo and the scriptName property is set to the prefix. The script name should begin with "/".
location: Path Path to where the application home directory is. This sets the dir property to the location argument.

setStatus(status: Number): Void
Description
Convenience routine to set the (proposed) Http response status code. This is equivalent to assigning to the status property.

setupFlash()
Description
Prepare the flash message area. This copies flash messages from the session state store into the flash store.

trace(options: Object): Void
Description
Configure request tracing for the request. The default is to trace the first line of requests and responses at level 2 and to trace headers at level 3. The options argument contains optional properties. These may contain an object hash which describes the following fields:.
Parameters
options: Object Set of trace options with properties for: The connection property specifies that new connections should be traced. The error property specifies that new connections should be traced. The info property specifies that new connections should be traced. The rxFirst property specifies that the first line of the request should be traced. The rxHeaders property specifies that the headers (including first line) of the request should be traced. The rxBody property specifies that the body content of the request should be traced. The txFirst property specifies that the first line of the response should be traced. The txHeaders property specifies that the headers (including first line) of the response should be traced. The txBody property specifies that the body content of the request should be traced. The complete property specifies that the body content of the request should be traced. The size property specifies a maximum body size in bytes that will be traced. Content beyond this limit will not be traced.
Example
trace({
    "rxHeaders": 3, "rxBody": 4, size: 1000000 
})

warn(msg: String): Void
Description
Set a warning flash notification. Flash messages persist for only one request and are a convenient way to pass state information or feedback messages to the next request. To use flash messages, setupFlash() and finalizeFlash() must be called before and after the request is processed. HttpServer.process will call setupFlash and finalizeFlash automatically.
Parameters
msg: String Message to store.

write(data: Array): Number
Description
Write data to the stream.Write data to the client. If the stream can accept all the write data, the call returns immediately with the number of bytes written. If writing more data than the stream can absorb in sync mode, the call will block until the data is written. If writing more data than the stream can absorb in async mode, the call will not block and will buffer the data and return immediately. Some streams will require a flush() call to actually send the data. A "writable" event will be issued when the stream can again absorb more data.This will buffer the written data until either flush() or finalize() is called. 0
Parameters
data: Array Data to write.
Events
readableIssued when data is written and a consumer can read without blocking.
writableIssued when the stream becomes empty and it is ready to be written to.
Returns
A count of the bytes actually written.
Throws
IOError: if there is an I/O error.

writeError(status: Number, msgs: Array): Void
Description
Write an error message back to the user and finalize the request. The output is Html escaped for security.
Parameters
status: Number Http status code.
msgs: Array Messages to send with the response. The messages may be modified for readability if it contains an exception backtrace.

writeFile(file: Path): Boolean
Description
Send a static file back to the client. This is a high performance way to send static content to the client by using the "sendConnector". To be effective, this call must be invoked prior to sending any data or headers to the client, otherwise it will be ignored and the slower "netConnector" will be used instead.
Parameters
file: Path Path to the file to send back to the client.
Returns
True if the Send connector can successfully be used. 8.

writeResponse(response: Object): Void
Description
Send a response to the client. This can be used instead of setting status and calling setHeaders() and write(). The response argument is an object hash containing status, headers and body properties. The respond method replaces previously defined status and headers.
Options
statusNumeric Http status code (e.g. 200 for a successful response).
headerObject hash of Http headers.
bodyBody content.

writeSafe(data: Array): Number
Description
Write safely. Write HTML escaped data back to the client.
Parameters
data: Array Objects to HTML encode and write back to the client. 0.