infinity.http¶
Provides HTTP client and server functionality.
Module: infinity.http
HTTP Server Architecture Overview¶
The INFINITY.JS HTTP server uses a sophisticated multi-threaded architecture to handle concurrent client connections efficiently. Each worker thread runs its own instance of the MuJS JavaScript engine, providing true parallel execution. Understanding this architecture is essential for building high-performance web applications.
Thread Pool Architecture¶
graph TB
subgraph "Main Program Thread"
MainJS["main.js<br/>JavaScript Runtime"]
ServerObj["server = new infinity.http.server()<br/>maxConnections, poolSize"]
Listener["Listener Thread<br/>(Port: 80/443)"]
end
subgraph "Connection Queue"
Queue["Incoming Connections<br/>(max: maxConnections)"]
end
subgraph "Worker Thread Pool"
Worker1["Worker Thread 1<br/>JavaScript Engine"]
Worker2["Worker Thread 2<br/>JavaScript Engine"]
Worker3["Worker Thread 3<br/>JavaScript Engine"]
WorkerN["Worker Thread N<br/>JavaScript Engine<br/>(poolSize total)"]
end
subgraph "Request Processing"
Handler1["Request Handler<br/>Service/Route Logic"]
Handler2["Request Handler<br/>Service/Route Logic"]
Handler3["Request Handler<br/>Service/Route Logic"]
HandlerN["Request Handler<br/>Service/Route Logic"]
end
Client1["Client 1<br/>HTTP Request"]
Client2["Client 2<br/>HTTP Request"]
Client3["Client 3<br/>HTTP Request"]
ClientN["Client N<br/>HTTP Request"]
MainJS --> ServerObj
ServerObj --> Listener
Client1 -->|"TCP Connection"| Listener
Client2 -->|"TCP Connection"| Listener
Client3 -->|"TCP Connection"| Listener
ClientN -->|"TCP Connection"| Listener
Listener -->|"Accept & Queue"| Queue
Queue -.->|"Assign Connection"| Worker1
Queue -.->|"Assign Connection"| Worker2
Queue -.->|"Assign Connection"| Worker3
Queue -.->|"Assign Connection"| WorkerN
Worker1 --> Handler1
Worker2 --> Handler2
Worker3 --> Handler3
WorkerN --> HandlerN
Handler1 -.->|"Response"| Client1
Handler2 -.->|"Response"| Client2
Handler3 -.->|"Response"| Client3
HandlerN -.->|"Response"| ClientN
style MainJS fill:#4a90e2
style Listener fill:#ab47bc
style Queue fill:#ffa726
style Worker1 fill:#7cb342
style Worker2 fill:#7cb342
style Worker3 fill:#7cb342
style WorkerN fill:#7cb342
style Handler1 fill:#26c6da
style Handler2 fill:#26c6da
style Handler3 fill:#26c6da
style HandlerN fill:#26c6da Request Lifecycle¶
sequenceDiagram
participant Client
participant Listener
participant Queue
participant WorkerPool as Worker Pool
participant Worker as Worker Thread
participant JSEngine as JavaScript Engine
participant Service as Service Handler
Client->>Listener: TCP Connection (HTTP Request)
Listener->>Queue: Accept & Queue Connection
alt Worker Available
Queue->>WorkerPool: Request Worker Thread
WorkerPool->>Worker: Assign Connection
Worker->>JSEngine: Initialize Runtime Context
JSEngine->>Service: Execute Handler Function
Note over Service: Process Request<br/>- Parse params<br/>- Validate types<br/>- Execute business logic
Service-->>JSEngine: Return Result
JSEngine-->>Worker: Serialize Response
Worker-->>Client: HTTP Response
Worker->>WorkerPool: Return to Pool
else No Worker Available
Note over Queue: Connection waits in queue<br/>(up to maxConnections)
end Architecture Details¶
Listener Thread: - Single dedicated thread that accepts incoming TCP connections - Listens on the configured port (default: 80 for HTTP, 443 for HTTPS) - Accepts connections and places them in the connection queue - Non-blocking operation ensures continuous availability
Connection Queue: - Thread-safe FIFO queue holding incoming connections - Maximum number of simultaneous connections controlled by maxConnections parameter (0 = unlimited) - Connections wait here until a worker thread becomes available - Prevents resource exhaustion during traffic spikes
Worker Thread Pool: - Pre-allocated pool of threads ready to process requests - Pool size controlled by poolSize parameter (if poolSize is 0, no thread pool is used and a new thread is created for each connection) - Each worker thread contains: - Independent JavaScript Engine: Complete MuJS runtime instance - Isolated Runtime Context: Separate memory space per thread - Request/Response Objects: infinity.http.request and infinity.http.response namespaces - Registered Handlers: Access to services, routes, and middleware
Request Processing: 1. Worker thread receives connection from queue 2. Parses HTTP request (headers, body, parameters) 3. Validates request against registered types and constraints 4. Routes request to appropriate handler (static file, JSON-RPC, REST, etc.) 5. Executes handler function in JavaScript engine 6. Serializes response and sends to client 7. Returns to pool for next connection
Key Parameters:
| Parameter | Description | Default | Impact |
|---|---|---|---|
maxConnections | Maximum simultaneous connections | 0 (unlimited) | Connections beyond this limit are rejected |
poolSize | Number of worker threads | 0 (no thread pool, one thread per connection) | Determines concurrency; more threads = more parallel requests but higher memory usage |
maxContentLength | Maximum request body size (bytes) | 104857600 (100 MB), 0 = unlimited | Protects against memory exhaustion from large payloads |
slowRequestTime | Log threshold for slow requests (seconds) | 0 (disabled) | Helps identify performance bottlenecks |
Performance Considerations:
- Thread Pool Sizing: Set
poolSizebased on CPU cores and workload: - CPU-intensive:
poolSize ≈ CPU cores - I/O-intensive:
poolSize ≈ 2-4 × CPU cores -
Mixed workload: Start with
poolSize = CPU coresand tune based on metrics -
Connection Limits: Set
maxConnectionshigh enough for peak traffic: - Typical: 1024-2048 for most applications
-
High-traffic: 4096+ with adequate system resources
-
Memory Usage: Each worker thread consumes:
- JavaScript engine overhead: ~2-5 MB
- Request/response buffers: Varies by
maxContentLength - Total estimate:
poolSize × (5 MB + average request size)
Example Configuration:
infinity.loadModule('infinity.http');
// High-performance server for CPU-intensive workloads
let server = new infinity.http.server(
true, // ssl
false, // verifyCertificate
true, // allowCrossOrigin
true, // compress
true, // accessLog
443, // port
2048, // maxConnections (2K simultaneous)
16, // poolSize (16 worker threads)
10 * 1024 * 1024, // maxContentLength (10MB)
2.0 // slowRequestTime (2 seconds)
);
See Also: - Performance Benchmarks - Detailed HTTP server performance metrics - Performance Best Practices - Optimization guidelines
client¶
Allows for your instance of INFINITY.JS to act as an http-client. Lets you send requests and receive data.
All request methods work synchronously: they block until the response has been received. After each request, the properties responseCode, responseText, contentType, contentDisposition and contentLength of the client instance contain the values of the last response (responseCode and responseText are set even if the request fails with an exception). Redirects are followed automatically (up to 3) and cookies are kept between requests of the same instance.
Properties:
- accept
- allowUnsafeLegacyRenegotiation
- authMode
- charset
- contentDisposition
- contentLength
- contentType
- date
- etag
- expires
- handleProtocolErrorContent
- lastModified
- location
- logFile
- maxContentLength
- password
- proxyPort
- proxyServer
- responseCharset
- responseCode
- responseText
- timeout
- useLegacyServerConnect
- userAgent
- username
- verifyServerCertificate
Methods:
- constructor()
- free()
- get()
- getAllRequestHeaders()
- getAllResponseHeaders()
- getFile()
- getRequestHeader()
- getResponseHeader()
- getStream()
- head()
- jsonRpc()
- options()
- patch()
- patchFile()
- patchStream()
- post()
- postFile()
- postMultipartFormData()
- postStream()
- put()
- putFile()
- putStream()
- remove()
- reset()
- setRequestHeader()
Example:
infinity.loadModule('infinity.http');
let myClient = new infinity.http.client();
let html = myClient.get('http://localhost');
console.debug(html);
//<!doctype html>
//<html lang="de_DE"...
Properties
accept¶
Type: string
Gets or sets the Accept request header value. Default: '' (no Accept header is sent, which servers treat like */*).
allowUnsafeLegacyRenegotiation¶
Type: boolean
Allows the deprecated ssl unsafe legacy renegotiation. This should be avoided and the server's ssl version should be fixed, instead. If that is not possible, then this option can be used to let the http client establish a connection nonetheless. Default: false.
authMode¶
Type: infinity.http.client.authMode
Specifies the authentification mode for the connection to the server. The username and password properties are only sent if this is set to basic or digest. Default: none.
charset¶
Type: string
Gets or sets the charset value of the Content-Type request header. Default: ''.
contentDisposition¶
Type: string
Gets or sets the Content-Disposition request header value. After a request, reading this property returns the Content-Disposition header value of the response; the value set by the script is still sent with the following requests (since 3.11; before, the response value was sent as request header of the next request).
contentLength¶
Type: number
Gets the Content-Length header value of the last response.
contentType¶
Type: string
Gets or sets the Content-Type request header value. After a request, reading this property returns the Content-Type header value of the response; the value set by the script is still sent with the following requests (since 3.11; before, the response value was sent as request header of the next request).
date¶
Type: number
Gets the Date header value of the last response as timestamp in milliseconds since 1970-01-01 (UTC). Only set by get().
etag¶
Type: string
Gets the ETag header value of the last response. Only set by get().
expires¶
Type: number
Gets the Expires header value of the last response as timestamp in milliseconds since 1970-01-01 (UTC). Only set by get().
handleProtocolErrorContent¶
Type: boolean
If set to true, then http error codes (http status codes 400 or higher) will no longer throw an exception. Instead, the request method returns the response body and the responseCode and responseText properties will contain the http status code and status text. Default: false.
lastModified¶
Type: number
Gets the Last-Modified header value of the last response as timestamp in milliseconds since 1970-01-01 (UTC). Only set by get().
location¶
Type: string
Gets the Location header value of the last response. Only set by get().
logFile¶
Type: string
If set to a file name, the raw data sent and received by the client is logged to this file. Set it to an empty string (the default) to stop logging.
maxContentLength¶
Type: number
If this property is set to a value other than zero (the default), then the client will not read the response body if the Content-Length header of the response exceeds the given number of bytes.
password¶
Type: string
Sets the password for the chosen authentification type.
proxyPort¶
Type: number
Sets the port number for the connection with a proxy. Default: 0.
proxyServer¶
Type: string
Sets the IP or host name of a proxy server. Default: '' (no proxy).
responseCharset¶
Type: string
If set (e.g. 'utf-8'), the response body is decoded using this charset instead of the charset given in the Content-Type header of the response. Default: ''.
responseCode¶
Type: number
Gets the HTTP status code of the last response.
responseText¶
Type: string
Gets the HTTP status text of the last response (e.g. 'HTTP/1.1 200 OK').
timeout¶
Type: number
Sets the connect and read timeout for requests in milliseconds. Default: 5000.
useLegacyServerConnect¶
Type: boolean
Allows deprecated, unsafe ssl connections. This should be avoided and the server's ssl version should be fixed, instead. If that is not possible, then this option can be used to let the http client establish a connection nonetheless. Default: false.
userAgent¶
Type: string
Gets or sets the User-Agent request header value. Default: 'INFINITY.JS http client'.
username¶
Type: string
Sets the user name for the chosen authentification type.
verifyServerCertificate¶
Type: boolean
This option will turn on ssl certificate validation, which will result in a connection error if the server's ssl certificate is not valid (e.g. self-signed). Default: false.
Methods
constructor()¶
Lets you create an INFINITY.JS HTTP client object instance.
Signature:
constructor()
Example:
infinity.loadModule('infinity.http');
let myClient = new infinity.http.client();
free()¶
Disconnects the client and frees the memory previously occupied by the HTTP client object instance. The instance must not be used afterwards.
Signature:
free(): void
Example:
myClient.free();
get()¶
Sends a GET HTTP request for the given URL, including the previously set HTTP-headers, and returns the response body. In addition to the common response properties, this method also sets the location, date, lastModified, expires and etag properties.
Signature:
get( url: string ): string
Parameters:
- url:
stringThe URL to send the request for.
Return type: string
Example:
let html = myClient.get('http://localhost');
console.debug(html);
getAllRequestHeaders()¶
Returns an array containing the names of all HTTP request headers sent with the last request.
Signature:
getAllRequestHeaders(): infinity.http.stringArray
Return type: infinity.http.stringArray
Example:
let html = myClient.get('http://localhost');
let requestHeaders = myClient.getAllRequestHeaders();
console.debug(requestHeaders);
getAllResponseHeaders()¶
Returns an array containing the names of all HTTP response headers of the last response.
Signature:
getAllResponseHeaders(): infinity.http.stringArray
Return type: infinity.http.stringArray
Example:
let html = myClient.get('http://localhost');
let responseHeaders = myClient.getAllResponseHeaders();
console.debug(responseHeaders);
getFile()¶
Sends a GET request to the given URL and writes the response body to the file at the specified location. An existing file is overwritten. If the request fails, the file is deleted and an exception is thrown.
Signature:
getFile( url: string, fileName: string ): void
Parameters:
-
url:
stringThe URL from which the contents have to be saved.
-
fileName:
stringFilename, relative path (location relative to the folder with the used INFINITY.JS executable file) or absolute path to the file which should contain the retrieved contents.
Example:
myClient.getFile('http://localhost', 'index.html');
getRequestHeader()¶
Returns the value of the specified HTTP request header of the last request (an empty string if the header was not sent).
Signature:
getRequestHeader( name: string ): string
Parameters:
- name:
stringThe name of the request header to be examined.
Return type: string
Example:
let requestHeader = myClient.getRequestHeader('User-Agent');
console.debug(requestHeader);
getResponseHeader()¶
Returns the value of the specified HTTP response header of the last response (an empty string if the header does not exist).
Signature:
getResponseHeader( name: string ): string
Parameters:
- name:
stringThe name of the response header to be examined.
Return type: string
Example:
let responseHeader = myClient.getResponseHeader('Expires');
console.debug(responseHeader);
getStream()¶
Sends a GET request to the specified URL and writes the response body to the given stream. Afterwards, the stream position is set to the beginning of the stream.
Signature:
getStream( url: string, stream: infinity.stream ): void
Parameters:
-
url:
stringThe url to save from.
-
stream:
infinity.streamThe stream object to write to. See infinity.stream.
Example:
let stream = new infinity.stream();
myClient.getStream('http://localhost/data', stream);
head()¶
Sends a HEAD request to the given URL and returns the response headers as an array of strings in the format 'Name: value'.
Signature:
head( url: string ): infinity.http.stringArray
Parameters:
- url:
stringThe URL to send the request to.
Return type: infinity.http.stringArray
Example:
let headers = myClient.head('http://localhost');
console.debug(JSON.stringify(headers));
jsonRpc()¶
Sends a JSON-RPC call (as POST request with content type application/json) to the specified URL and returns the parsed JSON response object (including the result or error member of the JSON-RPC response).
Signature:
jsonRpc( url: string, method: string, params?: infinity.http.paramArray, version?: infinity.http.client.version ): object
Parameters:
-
url:
stringThe URL to send the request to.
-
method:
stringThe remote procedure to be executed on the other endpoint.
-
params:
infinity.http.paramArray, optionalThe parameters to be passed to the remote procedure. If omitted or not an array, an empty array is sent.
-
version:
infinity.http.client.version, optionalSpecifies the version of JSON-RPC to use. Default:
jsonRpc2_0.
Return type: object
Example:
let response: any = myClient.jsonRpc('http://localhost/v1/jsonrpc', 'system.getVersion', [], infinity.http.client.version.jsonRpc2_0);
console.debug(JSON.stringify(response.result));
options()¶
Sends an OPTIONS request to the given URL and returns the response body.
Signature:
options( url: string ): string
Parameters:
- url:
stringThe URL to send the request to.
Return type: string
Example:
myClient.options('http://localhost/');
post()¶
Sends a POST request with the given string as request body to the given URL and returns the response body.
Signature:
post( url: string, value: string, encoding?: infinity.encoding ): string
Parameters:
-
url:
stringThe URL to send the request to.
-
value:
stringThe request body (e.g. URL encoded form data or JSON).
-
encoding:
infinity.encoding, optionalThe encoding used to convert the request body to bytes. Default: UTF-8.
Return type: string
Example:
myClient.contentType = 'application/x-www-form-urlencoded';
let response = myClient.post('http://localhost/', "key=value&anotherkey=anothervalue");
console.debug(response);
postFile()¶
Sends a POST request with the content of the specified file as request body to the given URL and returns the response body.
Signature:
postFile( url: string, fileName: string ): string
Parameters:
-
url:
stringThe URL to send the request to.
-
fileName:
stringFilename, relative path (location relative to the folder with the used INFINITY.JS executable file) or absolute path to the file to be uploaded.
Return type: string
Example:
let response = myClient.postFile('http://localhost/upload', "test.txt");
console.debug(response);
postMultipartFormData()¶
Sends a multipart/form-data POST request to the given URL and returns the response body. Each element of the data array becomes one form field (see formDataArray). Elements without a fieldName are ignored.
Signature:
postMultipartFormData( url: string, data: infinity.http.formDataArray ): string
Parameters:
-
url:
stringThe URL to send the request to.
-
data:
infinity.http.formDataArrayAn array containing the form fields to be sent.
Return type: string
Example:
let formData = [
{ fieldName: 'name', fieldValue: 'value1' },
{ fieldName: 'text', fieldValue: '<b>Hello</b>', charset: 'utf-8', contentType: 'text/html' },
{ fieldName: 'upload', fileName: 'test.txt', contentType: 'text/plain' }
];
let response = myClient.postMultipartFormData('http://localhost/', formData);
console.debug(response);
postStream()¶
Sends a POST request with the content of the request stream (read from its beginning) as request body to the given URL and writes the response body to the response stream. Afterwards, the response stream is positioned at its beginning.
Signature:
postStream( url: string, request: infinity.stream, response: infinity.stream ): void
Parameters:
- url:
stringThe URL to send the request to.
- request:
infinity.streamThe stream to be uploaded. See infinity.stream.
- response:
infinity.streamThe stream that receives the response body.
Example:
let request = new infinity.stream();
let response = new infinity.stream();
request.writeRawString('{"key": "value"}');
myClient.contentType = 'application/json';
myClient.postStream('http://localhost/upload', request, response);
console.debug(response.readRawString());
patch()¶
Sends a PATCH request with the given string as request body to the given URL and returns the response body.
Signature:
patch( url: string, value: string, encoding?: infinity.encoding ): string
Parameters:
-
url:
stringThe URL to send the request to.
-
value:
stringThe request body.
-
encoding:
infinity.encoding, optionalThe encoding used to convert the request body to bytes. Default: UTF-8.
Return type: string
Example:
let response = myClient.patch('http://localhost/', "patchRequestDataString");
console.debug(response);
patchFile()¶
Sends a PATCH request with the content of the specified file as request body to the given URL and returns the response body.
Signature:
patchFile( url: string, fileName: string ): string
Parameters:
-
url:
stringThe URL to send the request to.
-
fileName:
stringFilename, relative path (location relative to the folder with the used INFINITY.JS executable file) or absolute path to the file to be uploaded.
Return type: string
Example:
let response = myClient.patchFile('http://localhost/', "test.txt");
console.debug(response);
patchStream()¶
Sends a PATCH request with the content of the request stream (read from its beginning) as request body to the given URL and writes the response body to the response stream. Afterwards, the response stream is positioned at its beginning.
Signature:
patchStream( url: string, request: infinity.stream, response: infinity.stream ): void
Parameters:
- url:
stringThe URL to send the request to.
- request:
infinity.streamThe stream to be uploaded. See infinity.stream.
- response:
infinity.streamThe stream that receives the response body.
Example:
myClient.patchStream('http://localhost/resource/1', request, response);
put()¶
Sends a PUT request with the given string as request body to the given URL and returns the response body.
Signature:
put( url: string, value: string, encoding?: infinity.encoding ): string
Parameters:
-
url:
stringThe URL to send the request to.
-
value:
stringThe request body.
-
encoding:
infinity.encoding, optionalThe encoding used to convert the request body to bytes. Default: UTF-8.
Return type: string
Example:
let response = myClient.put('http://localhost/', "putRequestDataString");
console.debug(response);
putFile()¶
Sends a PUT request with the content of the specified file as request body to the given URL and returns the response body.
Signature:
putFile( url: string, fileName: string ): string
Parameters:
-
url:
stringThe URL to send the request to.
-
fileName:
stringFilename, relative path (location relative to the folder with the used INFINITY.JS executable file) or absolute path to the file to be uploaded.
Return type: string
Example:
let response = myClient.putFile('http://localhost/', "test.txt");
console.debug(response);
putStream()¶
Sends a PUT request with the content of the request stream (read from its beginning) as request body to the given URL and writes the response body to the response stream. Afterwards, the response stream is positioned at its beginning.
Signature:
putStream( url: string, request: infinity.stream, response: infinity.stream ): void
Parameters:
- url:
stringThe URL to send the request to.
- request:
infinity.streamThe stream to be uploaded. See infinity.stream.
- response:
infinity.streamThe stream that receives the response body.
Example:
myClient.putStream('http://localhost/upload', request, response);
remove()¶
Sends a DELETE request to the given URL and returns the response body.
Signature:
remove( url: string ): string
Parameters:
- url:
stringThe URL to send the request to.
Return type: string
Example:
myClient.remove('http://localhost/resource/123');
reset()¶
Clears the request and response headers and resets the properties responseCode, responseText, responseCharset, username, password, authMode, proxyServer, proxyPort, userAgent, charset, contentType, contentDisposition, contentLength, location, date, lastModified, expires and etag to their default values. Other properties (e.g. timeout, maxContentLength, accept, logFile or the SSL options) are not changed.
Signature:
reset(): void
Example:
myClient.reset();
setRequestHeader()¶
Sets the value of the specified header for future requests.
Signature:
setRequestHeader( name: string, value: string ): void
Parameters:
-
name:
stringThe name of the header to be set.
-
value:
stringThe value of the header to be set.
Example:
myClient.setRequestHeader('accept-encoding', 'gzip, deflate, br');
server¶
Allows for your instance of INFINITY.JS to act as an HTTP-server. Lets you receive requests and send data. Can register handlers for static files, single page applications, custom scripts, REST requests, the JSON-RPC protocol, API descriptions and a status report (JSON-RPC, REST and API handlers require the simultaneous usage of registerHandler() and registerService()). JSON-RPC and REST handlers can be combined in one service.
A request is passed to the handler whose registered path matches the request path exactly, otherwise to the handler with the longest registered path that is a prefix of the request path. If no handler matches, the server responds with status code 404.
The server instance has no free() method; it is released when the object is garbage collected.
Methods:
Example for a static file server and status report functionality:
infinity.loadModule('infinity.http');
let myServer = new infinity.http.server(false, false, false, false, false, 80, 1024, 64, 104857600, 5.0);
myServer.registerHandler(infinity.http.server.handler.staticFile, '/', '../web/', 60.0, 256144);
myServer.registerHandler(infinity.http.server.handler.status, '/status');
myServer.start();
while (!infinity.terminated) {
infinity.event.processQueue();
infinity.sleep(25);
}
myServer.stop();
+ example
+ ts
- main.ts
+ web
- index.html
http://localhost/status, or by a GET-request. Example for a server with custom options:
infinity.loadModule('infinity.http');
let myServer = new infinity.http.server(false, false, false, false, false, 80, 1024, 64, 104857600, 5.0);
myServer.registerHandler(infinity.http.server.handler.custom, '/custom', '/custom.js');
myServer.start();
while (!infinity.terminated) {
infinity.event.processQueue();
infinity.sleep(25);
}
myServer.stop();
custom.ts:
console.debug(infinity.http.request.httpAcceptEncoding);
infinity.http.response.contentType = 'text/plain; charset="utf-8"';
infinity.http.response.encoding = infinity.encoding.utf8;
infinity.http.response.contentText = 'Hello World! ü ö ä ß €';
Folder structure:
+ example
+ ts
- main.ts
- custom.ts
Can be viewed in a webbrowser under for example http://localhost/custom or by a GET-request.
Example for a JSON-RPC endpoint with a custom defined service:
infinity.loadModule('infinity.http');
let myServer = new infinity.http.server();
myServer.registerHandler(infinity.http.server.handler.jsonRpc, '/v1/jsonrpc');
myServer.registerService('system', 'system', 'system.js', [
{name: 'shutdown'},
{name: 'getVersion', result: 'string'}
]);
myServer.start();
while (!infinity.terminated) {
infinity.event.processQueue();
infinity.sleep(25);
}
myServer.stop();
system.ts:
namespace system {
export function shutdown(): void {
infinity.terminate();
}
export function getVersion(): string {
return '1.0.0 build 1234';
}
}
Folder structure:
+ example
+ ts
- main.ts
- system.ts
Can be used by a POST-request
{"jsonrpc": "2.0", "method": "system.getVersion"}
http://localhost/v1/jsonrpc. Example for a combined REST and JSON-RPC endpoint with a custom defined service:
infinity.loadModule('infinity.http');
let myServer = new infinity.http.server();
myServer.registerHandler(infinity.http.server.handler.staticFile, '/', '../web/');
myServer.registerHandler(infinity.http.server.handler.jsonRpc, '/v1/jsonrpc');
myServer.registerHandler(infinity.http.server.handler.rest, '/v1/rest');
myServer.registerService('users', 'users', 'users.js', [
{name: 'add', params: ['user: object'], result: 'number', rest: 'post'},
{name: 'put', params: ['user: object'], rest: 'put'},
{name: 'get', params: ['id: number'], result: 'object', rest: 'get'},
{name: 'list', result: 'array', rest: 'getList'},
{name: 'remove', params: ['id: number'], rest: 'delete'}
]);
myServer.start();
while (!infinity.terminated) {
infinity.event.processQueue();
infinity.sleep(25);
}
users.ts:
namespace users {
export function add(user: object): number {
console.debug('users.add: ' + JSON.stringify(user));
return 1;
}
export function put(user: object): void {
console.debug('users.put: ' + JSON.stringify(user));
}
export function get(id: number): object {
console.debug('users.get: ' + id);
return {id: 1, username: 'user1', name: 'The User Name'};
}
export function remove(id: number): void {
console.debug('users:remove: ' + id);
}
export function list(): Array<object> {
console.debug('users.list');
let users = [];
users.push({id: 1, username: 'user1', name: 'The User Name'});
users.push({id: 2, username: 'user2', name: 'Some User Name'});
users.push({id: 3, username: 'user3', name: 'Another User Name'});
return users;
}
}
Folder structure:
+ example
+ ts
- main.ts
- users.ts
http://localhost/v1/rest/users/1 or JSON-RPC POST-requests like {"jsonrpc": "2.0", "method": "users.get", "params": [1], "id": 1}
http://localhost/v1/jsonrpc. Methods
constructor()¶
Lets you create an INFINITY.JS HTTP server object instance. Takes the most important parameters for the server to function.
Signature:
constructor( ssl?: boolean, verifyCertificate?: boolean, allowCrossOrigin?: boolean, compress?: boolean, accessLog?: boolean, port?: number, maxConnections?: number, poolSize?: number, maxContentLength?: number, slowRequestTime?: number, minProtocol?: infinity.http.server.protocol, maxProtocol?: infinity.http.server.protocol, maxRateCounter?: number )
Parameters:
-
ssl:
boolean, optionalFor using SSL connections. Default:
false. If enabled, the server initially uses the certificate filesinfinity.crt,infinity.keyandinfinity.root.crtfrom theresourcesfolder next to the folder of the INFINITY.JS executable. Use setCertificate() to set other certificate files. -
verifyCertificate:
boolean, optionalIf
true(and a root certificate file exists), clients must present a valid SSL client certificate. Default:false. -
allowCrossOrigin:
boolean, optionalFor allowing cross-origin-requests (CORS headers). Default:
false. -
compress:
boolean, optionalFor turning gzip/deflate compression of responses on or off. Default:
false. -
accessLog:
boolean, optionalFor turning on or off the logging of all requests to the console/log file. Default:
false. -
port:
number, optionalSpecifies the port to listen on. Default:
443ifsslistrue, otherwise80. -
maxConnections:
number, optionalSpecifies the maximum number of simultaneous connections. Default:
0(unlimited). -
poolSize:
number, optionalSpecifies the number of worker threads to be held ready. Default:
0(no thread pool, a new thread is created for each connection). -
maxContentLength:
number, optionalSpecifies the maximum number of bytes (content-length header) that the server accepts in http requests. Default:
104857600(100 MB),0= unlimited. -
slowRequestTime:
number, optionalSpecifies how many seconds the processing of a request is allowed to take without being logged as "slow". Accepts decimals with
.as well. Default:0(slow requests are not logged). -
minProtocol:
infinity.http.server.protocol, optionalThe minimum SSL/TLS version to support. Default:
tls1. -
maxProtocol:
infinity.http.server.protocol, optionalThe maximum SSL/TLS version to support. Default:
tls1_3. -
maxRateCounter:
number, optionalThe maximum number of rate counters (one per handler and client IP address) tracked for rate limiting (see the
limit,periodanddelayparameters of registerHandler()). If more addresses are tracked, all rate counters are reset. Default:0(unlimited).
Example:
infinity.loadModule('infinity.http');
let myServer = new infinity.http.server(false, false, false, false, true, 80, 1024, 64, 1024 * 1024, 5.0);
registerHandler()¶
Registers a handler for client requests on the given path. The meaning of the parameters following path depends on the handler type:
jsonRpc,rest,apiandstatus:registerHandler(handler, path, limit?, period?, delay?)custom:registerHandler(handler, path, alias, limit?, period?, delay?)staticFileandspa:registerHandler(handler, path, alias, expire?, maxCacheSize?, headers?, limit?, period?, delay?)
A handler registered for an already registered path replaces the previous handler.
Signatures:
registerHandler( handler: infinity.http.server.handler, path: string, limit?: number, period?: number, delay?: number ): void
registerHandler( handler: infinity.http.server.handler, path: string, alias: string, limit?: number, period?: number, delay?: number ): void
registerHandler( handler: infinity.http.server.handler, path: string, alias: string, expire?: number, maxCacheSize?: number, headers?: infinity.http.headerArray, limit?: number, period?: number, delay?: number ): void
Parameters:
-
handler:
infinity.http.server.handlerThe type of handler to register.
-
path:
stringThe request path the handler is registered for (e.g.
'/'or'/v1/jsonrpc'). -
alias:
stringOnly for
custom,staticFileandspahandlers. Forcustomhandlers: the path of the script file (relative to the folder of the main script) that is executed for each request. ForstaticFileandspahandlers: the path of the folder (relative to the folder of the main script) containing the files to be served. -
expire:
number, optionalOnly for
staticFileandspahandlers. The cache expiration time in whole seconds. After the specified period the file will have to be examined for changes at the next call. Default:0(files are not cached). -
maxCacheSize:
number, optionalOnly for
staticFileandspahandlers. The cache threshold in bytes. Files with sizes exceeding the specified number will not be cached. Default:0. -
headers:
infinity.http.headerArray, optionalOnly for
staticFileandspahandlers. Additional headers to be sent with every response of the handler. -
limit:
number, optionalThe maximum number of requests per client IP address that can be made to this handler in the defined period (rate limiting; every handler has its own counters). If the limit is exceeded, the request is answered with status code
429. Default:0(no rate limiting). -
period:
number, optionalThe rate limit time period in seconds.
-
delay:
number, optionalThe number of seconds the server waits before sending the
429response to a client that exceeded the rate limit (slows down clients that send too many requests).
Example:
myServer.registerHandler(infinity.http.server.handler.status, '/status', 10, 60, 3);
myServer.registerHandler(infinity.http.server.handler.staticFile, '/', '../web/', 60, 256144, [{name: "Cache-Control", value: "must-revalidate"}]);
Folder structure:
+ example
+ ts
- main.ts
+ web
- index.html
registerService()¶
Registers a service, allowing requests for execution of custom defined methods. Supports parameter and result type validation using built-in types, validation constraints, and custom types defined with registerTypes().
Signature:
registerService( name: string, namespace: string, path: string, methods: infinity.http.methodArray ): void
Parameters:
-
name:
stringThe name of the service.
-
namespace:
stringThe namespace for the service.
-
path:
stringThe path to the script file with the custom defined methods.
-
methods:
infinity.http.methodArrayAn array of method definitions. Each method can specify: -
name: Method name (required) -params: Array of parameter definitions in the format'name: type'(optional parameters:'name?: type', they must follow all required parameters) -result: Declared return type (only used for the description generated by theapihandler, return values are not validated) -rest: REST method mapping ('get','getList','post','put'or'delete') -httpEnvironment: If true, provides access toinfinity.http.requestandinfinity.http.responseinside the method
Parameter Type Syntax¶
Built-in types: - string - String value - number - Numeric value - boolean - Boolean value - object - Generic object - array - Generic array
Validation Constraints:
For numbers: - number{min,} - Minimum value (e.g., number{1,} = positive numbers) - number{,max} - Maximum value (e.g., number{,100} = at most 100) - number{min,max} - Range (e.g., number{18,120} = age range)
For strings: - string{min,} - Minimum length (e.g., string{1,} = non-empty) - string{,max} - Maximum length (e.g., string{,255} = max 255 chars) - string{min,max} - Length range (e.g., string{3,32} = username length)
For arrays: - array{min,max} - Number of array elements (e.g., array{1,10})
Custom types: - Reference types defined with registerTypes() (e.g., users.user, api.response). Use a custom type of kind array for arrays with typed elements.
Examples¶
Basic example without validation:
myServer.registerHandler(infinity.http.server.handler.jsonRpc, '/v1/jsonrpc');
myServer.registerService('system', 'system', 'system.js', [
{name: 'shutdown'},
{name: 'getVersion', result: 'string'}
]);
Example with validation constraints:
myServer.registerService('users', 'users', 'users.js', [
// Username and password with length validation
{
name: 'login',
params: ['username: string{3,32}', 'password: string{8,}'],
result: 'object'
},
// ID with range validation (positive numbers only)
{
name: 'get',
params: ['id: number{1,}'],
result: 'object',
rest: 'get'
},
// Age with realistic range
{
name: 'updateAge',
params: ['userId: number{1,}', 'age: number{0,150}'],
rest: 'put'
},
// Email with length constraint
{
name: 'updateEmail',
params: ['userId: number{1,}', 'email: string{5,255}'],
rest: 'put'
}
]);
Example with custom types:
// First, register custom types
myServer.registerTypes([
{
name: 'users.role',
kind: 'enum',
values: ['user = 1', 'admin = 2']
},
{
name: 'users.user',
kind: 'object',
properties: [
'id: number{0,}',
'username: string{3,32}',
'email: string{5,255}',
'role: users.role'
]
},
{
name: 'users.userList',
kind: 'array',
of: 'users.user'
}
]);
// Then use custom types in service methods
myServer.registerService('users', 'users', 'users.js', [
{
name: 'add',
params: ['user: users.user'], // Validates entire user object
result: 'number', // Returns user ID
rest: 'post'
},
{
name: 'get',
params: ['id: number{1,}'],
result: 'users.user', // Declared return type (not validated)
rest: 'get'
},
{
name: 'list',
result: 'users.userList', // Declared return type (not validated)
rest: 'getList'
},
{
name: 'update',
params: ['id: number{1,}', 'user: users.user'],
rest: 'put'
}
]);
Example with HTTP environment access:
myServer.registerService('files', 'files', 'files.js', [
{
name: 'upload',
params: ['filename: string{1,255}'],
result: 'object',
rest: 'post',
httpEnvironment: true // Enables access to request/response
}
]);
files.ts:
namespace files {
export function upload(filename: string): object {
// Access HTTP request data
let contentType = infinity.http.request.contentType;
let fileSize = infinity.http.request.contentLength;
// Access uploaded files
let uploadedFiles = infinity.http.request.files;
// Set response headers
infinity.http.response.contentType = 'application/json';
return {
success: true,
filename: filename,
size: fileSize
};
}
}
Validation Behavior¶
When clients call service methods through the jsonRpc or rest handler:
- Parameter Validation: All parameters are validated against their type definitions before the method is called
- Automatic Errors: Invalid requests are rejected with a descriptive error message (
resthandler: HTTP status code400,jsonRpchandler: JSON-RPC error code-32602) - Type Safety: Your service methods receive validated data
- No Result Validation: Return values are not validated
Example error messages:
Missing parameter username for method users.login
Invalid value for parameter id for method users.get, number expected
Value for parameter age using method users.updateAge is out of range
Length for parameter username using method users.login is out of range
system.ts:
namespace system {
export function shutdown(): void {
infinity.terminate();
}
export function getVersion(): string {
return '1.0.0 build 1234';
}
}
Folder structure:
+ example
+ ts
- main.ts
- system.ts
POST-request against /v1/jsonrpc:
{"jsonrpc": "2.0", "method": "system.getVersion"}
See also: registerTypes() for defining custom types with complex validation rules.
registerTypes()¶
Registers custom type definitions for request/response validation. This allows you to define complex data types with validation rules that are automatically enforced when clients call your service methods. Types can include enums, objects with property constraints, and arrays, and can reference other custom types.
Signature:
registerTypes( types: infinity.http.typesArray ): void
Parameters:
- types:
infinity.http.typesArrayAn array of type definitions. Each type definition specifies a name, kind, and kind-specific properties.
Type Kinds¶
enum - Enumeration with named values:
{name: 'users.role', kind: 'enum', values: ['undefined = 0', 'user = 1', 'admin = 2']}
array - Array of elements with specified type:
{name: 'users.idList', kind: 'array', of: 'number{1,}'}
object - Object with typed properties:
{name: 'users.user', kind: 'object', properties: ['id: number{0,}', 'username: string{1,32}']}
Validation Syntax¶
Numbers with range constraints: - number - Any number - number{min,} - Number with minimum value (e.g., number{1,} = minimum 1) - number{,max} - Number with maximum value (e.g., number{,100} = maximum 100) - number{min,max} - Number within range (e.g., number{0,10} = 0 to 10)
Strings with length constraints: - string - Any string - string{min,} - String with minimum length (e.g., string{1,} = non-empty) - string{,max} - String with maximum length (e.g., string{,64} = max 64 chars) - string{min,max} - String within length range (e.g., string{1,32} = 1 to 32 chars)
Optional properties: - property?: type - Optional property (e.g., name?: string{,64})
Custom type references: - Use registered type names (e.g., role: users.role)
Example:
infinity.loadModule('infinity.http');
let http = new infinity.http.server();
// Define custom types with validation
http.registerTypes([
// Enum type for user roles
{
name: 'users.role',
kind: 'enum',
values: ['undefined = 0', 'user = 1', 'admin = 2', 'super = 3']
},
// Enum type for user state
{
name: 'users.state',
kind: 'enum',
values: ['undefined = 0', 'active = 1', 'inactive = 2']
},
// Array of numbers (user IDs)
{
name: 'users.idList',
kind: 'array',
of: 'number{1,}' // Array of positive numbers
},
// Complex object type with validation
{
name: 'users.user',
kind: 'object',
properties: [
'id: number{0,}', // Non-negative number
'username: string{1,32}', // String 1-32 chars
'email: string{5,255}', // Email with length constraint
'name?: string{,64}', // Optional string, max 64 chars
'role?: users.role', // Optional enum (references users.role)
'state: users.state', // Required enum
'friendIds: users.idList' // Array (references users.idList)
]
},
// Array of user objects
{
name: 'users.userList',
kind: 'array',
of: 'users.user'
}
]);
// Register service using the custom types
http.registerService('users', 'users', 'users.js', [
{
name: 'add',
params: ['user: users.user'], // Validates against users.user type
result: 'number',
rest: 'post'
},
{
name: 'get',
params: ['id: number{1,}'],
result: 'users.user', // Declared return type (not validated)
rest: 'get'
},
{
name: 'list',
result: 'users.userList', // Declared return type (not validated)
rest: 'getList'
},
{
name: 'update',
params: ['id: number{1,}', 'user: users.user'],
rest: 'put'
}
]);
http.start();
users.ts:
namespace users {
export function add(user: object): number {
// user parameter is automatically validated against users.user type
// Engine guarantees that:
// - id is a non-negative number
// - username is 1-32 characters
// - email is 5-255 characters
// - role (if present) is a valid users.role enum value
// - state is a valid users.state enum value
// - All required properties are present
console.log('Adding user:', user);
return 1; // Return new user ID
}
export function get(id: number): object {
// Note: return values are not validated against the declared result type
return {
id: id,
username: 'john_doe',
email: 'john@example.com',
state: 1, // active
friendIds: [2, 3, 5]
};
}
export function list(): Array<object> {
return [
{id: 1, username: 'alice', email: 'alice@example.com', state: 1, friendIds: []},
{id: 2, username: 'bob', email: 'bob@example.com', state: 1, friendIds: [1]}
];
}
}
Validation Behavior¶
When a client calls a service method with registered types:
- Request Validation: The engine automatically validates incoming parameters against the registered types
- Type Checking: Ensures all required properties are present and have correct types
- Constraint Checking: Validates ranges for numbers and length constraints for strings
- Enum Validation: Ensures enum values are within the defined set
- Nested Validation: Recursively validates nested objects and arrays
- Error Response: Returns a descriptive error if validation fails (
resthandler: HTTP status code400,jsonRpchandler: JSON-RPC error code-32602)
Example validation errors: - Missing required property: Missing property username in parameter user for method users.add - Invalid enum value: Invalid enum value for parameter role for method users.add - Invalid type: Invalid value for parameter id for method users.get, number expected
Return values are not validated.
Benefits¶
- API Safety: Prevents invalid data from reaching your service methods
- Automatic Documentation: Types serve as self-documenting API specifications
- Client-Side Validation: Can be used to generate TypeScript interfaces or validation schemas
- Reduced Boilerplate: Eliminates manual parameter validation code
- Consistent Error Messages: Standardized validation error responses
unregisterTypes()¶
Unregisters a previously registered custom type definition.
Signature:
unregisterTypes( name: string ): void
Parameters:
- name:
stringThe name of the type to unregister.
Example:
http.unregisterTypes('users.user');
http.unregisterTypes('users.role');
Note: Service methods and types keep a reference to the type definitions they use. Unregister a type only after unregistering all services and types that reference it.
setCertificate()¶
Sets the SSL certificate for the current server instance using the corresponding files provided in the function parameters. Throws an error if the server was created without SSL. Files that do not exist are ignored.
Signature:
setCertificate( certFile: string, keyFile: string, rootCertFile?: string, verify?: boolean ): void
Parameters:
-
certFile:
stringThe path to the certificate file to be used.
-
keyFile:
stringThe path to the key file to be used.
-
rootCertFile:
string, optionalThe path to the root certificate file to be used.
-
verify:
boolean, optionalIf
true(and a root certificate file is given), clients must present a valid SSL client certificate. Default:false.
Example:
myServer.setCertificate('certFile.crt', 'keyFile.key', 'rootCertFile.crt', true);
start()¶
Starts the server instance with previously specified parameters.
Signature:
start(): void
Example:
myServer.start();
stop()¶
Shuts down the server instance.
Signature:
stop(): void
Example:
myServer.stop();
unregisterHandler()¶
Unregisters the specified registered handler, making the previously defined functionality unavailable.
Signature:
unregisterHandler( path: string ): void
Parameters:
- path:
stringThe request path for the client, which the handler has previously been registered for.
Example:
myServer.unregisterHandler('/');
unregisterService()¶
Unregisters the specified registered service, making the previously defined functionality unavailable.
Signature:
unregisterService( name: string ): void
Parameters:
- name:
stringThe name of the previously registered service.
Example:
myServer.unregisterService('system');
infinity.http.client¶
infinity.http.client.authMode¶
Values:
-
none:
0None of the below.
-
basic:
1Basic access authentication.
-
digest:
2Digest access authentication.
Example:
infinity.loadModule('infinity.http');
let authMode = infinity.http.client.authMode.none;
infinity.http.client.version¶
Values:
-
jsonRpc1_1:
0JSON-RPC version 1.1.
-
jsonRpc2_0:
1JSON-RPC version 2.0.
Example:
infinity.loadModule('infinity.http');
let version = infinity.http.client.version.jsonRpc1_1;
infinity.http.request¶
Read-only properties containing information from the incoming HTTP request. Only available inside scripts executed by a custom handler and inside service methods registered with httpEnvironment: true (for all server types: infinity.http.server, infinity.http2.server and infinity.scgi.server).
- contentBoundary
- contentDisposition
- contentEncoding
- contentFilename
- contentLength
- contentText
- contentTransferEncoding
- contentType
- cookies
- destination
- files
- gatewayInterface
- get
- headers
- httpAccept
- httpAcceptCharSet
- httpAcceptEncoding
- httpAcceptLanguage
- httpAuthorization
- httpConnection
- httpHost
- httpIfMatch
- httpIfModifiedSince
- httpIfNoneMatch
- httpIfUnmodifiedSince
- httpReferer
- httpUserAgent
- method
- pathInfo
- pathTranslated
- post
- range
- remoteAddr
- remoteHost
- remoteIdent
- remotePort
- remoteUser
- scgi
- scheme
- scriptFilename
- scriptName
- serverAddr
- serverAdmin
- serverName
- serverPort
- serverProtocol
- serverSignature
- serverSoftware
- uri
contentBoundary¶
Type: string
Gets the boundary parameter of the content-type HTTP-header value (multipart requests).
contentDisposition¶
Type: string
Gets the content-disposition HTTP-header value.
contentEncoding¶
Type: infinity.encoding
Gets the character encoding preferred for the response, determined from the accept-charset HTTP-header value. If the request has no accept-charset header, the charset of the content-type header of the request is used (default: UTF-8). This is also the default value of infinity.http.response.encoding in custom handler scripts.
contentFilename¶
Type: string
Gets the filename parameter of the Content-Disposition HTTP-header value.
contentLength¶
Type: number
Gets the content-length HTTP-header value (-1 if the header is missing).
contentText¶
Type: string
Gets the contents of the body of the request.
contentTransferEncoding¶
Type: string
Gets the content-transfer-encoding HTTP-header value.
contentType¶
Type: string
Gets the content-type HTTP-header value (without parameters like charset or boundary).
cookies¶
Type: infinity.http.cookiesArray
Gets the cookies sent with the request.
destination¶
Type: string
Gets the destination HTTP-header value (used by WebDAV clients).
files¶
Type: infinity.http.filesArray
Gets information about the files sent with the HTTP request.
gatewayInterface¶
Type: string
Gets the name and version of the gateway interface (only during SCGI operations).
get¶
Type: infinity.http.valuesArray
Gets the query parameters of the request URI as name-value pairs.
headers¶
Type: infinity.http.valuesArray
Gets all HTTP-headers of the request as name-value pairs.
httpAccept¶
Type: string
Gets the accept HTTP-header value.
httpAcceptCharSet¶
Type: string
Gets the accept-charset HTTP-header value.
httpAcceptEncoding¶
Type: string
Gets the accept-encoding HTTP-header value.
httpAcceptLanguage¶
Type: string
Gets the accept-language HTTP-header value.
httpAuthorization¶
Type: string
Gets the authorization HTTP-header value.
httpConnection¶
Type: string
Gets the connection HTTP-header value.
httpHost¶
Type: string
Gets the Host value of the HTTP request.
httpIfMatch¶
Type: string
Gets the if-match HTTP-header value.
httpIfModifiedSince¶
Type: number
Gets the if-modified-since HTTP-header value as timestamp in milliseconds since 1970-01-01 (UTC).
httpIfNoneMatch¶
Type: string
Gets the if-none-match HTTP-header value.
httpIfUnmodifiedSince¶
Type: number
Gets the if-unmodified-since HTTP-header value as timestamp in milliseconds since 1970-01-01 (UTC).
httpReferer¶
Type: string
Gets the referer HTTP-header value.
httpUserAgent¶
Type: string
Gets the user-agent HTTP-header value.
method¶
Type: string
Gets the HTTP request method (e.g. 'GET' or 'POST').
pathInfo¶
Type: string
In scripts of a custom handler: the URL decoded part of the request path following the path the handler is registered for (e.g. '/123' for a request to /custom/123 with a handler registered for /custom).
pathTranslated¶
Type: string
Represents a translation of the PathInfo property to a fully qualified path on the Web server.
post¶
Type: infinity.http.valuesArray
Gets the form fields of a request with the content type application/x-www-form-urlencoded or multipart/form-data as name-value pairs.
range¶
Type: infinity.http.rangeArray
Gets the byte ranges of the range HTTP-header value.
remoteAddr¶
Type: string
Gets the IP address of the remote machine making this request.
remoteHost¶
Type: string
Gets the hostname of the remote machine making this request (only during SCGI operations).
remoteIdent¶
Type: string
Gets the remote user name retrieved from the server (only during SCGI operations).
remotePort¶
Type: number
Gets the port over which the remote machine communicates.
remoteUser¶
Type: string
Gets the authenticated remote user name (only during SCGI operations).
scgi¶
Type: boolean
Indicates whether the request was received by an infinity.scgi.server.
scheme¶
Type: string
Gets the request scheme: 'HTTP', 'HTTPS' (infinity.http.server with SSL) or 'SCGI'.
scriptFilename¶
Type: string
Gets the SCRIPT_FILENAME value sent by the web server (only during SCGI operations).
scriptName¶
Type: string
Gets the path of the request URI without the query string (during SCGI operations: the SCRIPT_NAME value sent by the web server).
serverAddr¶
Type: string
Gets the local server address.
serverAdmin¶
Type: string
Gets the server administrator information sent by the web server (only during SCGI operations).
serverName¶
Type: string
Gets the domain name of the local server.
serverPort¶
Type: number
Gets the port over which the local server communicates.
serverProtocol¶
Type: string
Gets the protocol over which the local server communicates.
serverSignature¶
Type: string
Gets the signature of the local server (only during SCGI operations).
serverSoftware¶
Type: string
Gets the name representing the local server software.
uri¶
Type: string
Gets the URI of the HTTP request (path and query string).
infinity.http.response¶
The properties of the outgoing response from the INFINITY.JS server. Can be read and set. Only available inside scripts executed by a custom handler (see the alias parameter of registerHandler()) and inside service methods registered with httpEnvironment: true (for all server types: infinity.http.server, infinity.http2.server and infinity.scgi.server). The values are applied to the response after the script or method has finished.
- acceptRanges
- cacheControl
- code
- contentDisposition
- contentEncoding
- contentFilename
- contentLanguage
- contentRange
- contentStream
- contentText
- contentType
- cookies
- date
- encoding
- etag
- expires
- headers
- ignoreSlowRequest
- lastModified
- location
- pragma
- proxyAuthenticate
- refresh
- server
- transferEncoding
- wwwAuthenticate
acceptRanges¶
Type: string
Gets or sets the accept-ranges HTTP-header value.
cacheControl¶
Type: string
Gets or sets the cache-control HTTP-header value.
code¶
Type: number
Gets or sets the HTTP response status code.
contentDisposition¶
Type: string
Gets or sets the content-disposition HTTP-header value.
contentEncoding¶
Type: string
Gets or sets the content-encoding HTTP-header value.
contentFilename¶
Type: string
If set, the content of the file with this name is sent as response body (instead of contentText). Ignored if contentStream has been set.
contentLanguage¶
Type: string
Gets or sets the content-language HTTP-header value.
contentRange¶
Type: string
Gets or sets the content-range HTTP-header value.
contentStream¶
Type: infinity.stream
Sets the contents of the body of the response using a infinity.stream. The complete content of the stream (from its beginning) is copied when the property is assigned, so later changes of the stream have no effect. This property is write-only. If set, contentFilename and contentText are ignored.
contentText¶
Type: string
Gets or sets the contents of the body of the response. The text is converted using the encoding property.
contentType¶
Type: string
Gets or sets the content-type HTTP-header value.
cookies¶
Type: infinity.http.cookiesArray
Gets or sets the cookies to be set by the response (Set-Cookie headers). Initially an empty array. If path is omitted, '/' is used.
date¶
Type: number
Gets or sets the date HTTP-header value as timestamp in milliseconds since 1970-01-01 (UTC).
encoding¶
Type: infinity.encoding
Gets or sets the encoding used to convert contentText to bytes.
etag¶
Type: string
Gets or sets the etag HTTP-header value.
expires¶
Type: number
Gets or sets the expires HTTP-header value as timestamp in milliseconds since 1970-01-01 (UTC).
headers¶
Type: infinity.http.valuesArray
Gets or sets additional response headers as name-value pairs. Initially an empty array.
ignoreSlowRequest¶
Type: boolean
If set to true, the request is not logged as slow request even if it takes longer than the slowRequestTime set during the server instance creation.
lastModified¶
Type: number
Gets or sets the last-modified HTTP-header value as timestamp in milliseconds since 1970-01-01 (UTC).
location¶
Type: string
Gets or sets the location HTTP-header value.
pragma¶
Type: string
Gets or sets the pragma HTTP-header value.
proxyAuthenticate¶
Type: string
Gets or sets the proxy-authenticate HTTP-header value.
refresh¶
Type: string
Gets or sets the undocumented refresh HTTP-header value.
server¶
Type: string
Gets or sets the server HTTP-header value.
transferEncoding¶
Type: string
Gets or sets the transfer-encoding HTTP-header value.
wwwAuthenticate¶
Type: string
Gets or sets the WWW-Authenticate HTTP-header value.
infinity.http.server¶
infinity.http.server.handler¶
Values:
-
custom:
0A custom handler: the script file specified in the third function parameter (
alias) of registerHandler() is executed for each request. Inside the script,infinity.http.requestandinfinity.http.responseare available. -
staticFile:
1A handler for serving static file content from the folder specified in the
aliasparameter. For requests to a folder, theindex.htmlfile of the folder is served. -
jsonRpc:
2A handler for requests according to the JSON-RPC protocol (calls methods of the registered services).
-
rest:
3A handler for REST-requests (calls methods of the registered services according to their
restmapping). -
api:
4A handler that returns a JSON-WSP description of all registered services and methods (
GETrequests). -
status:
5A handler for server-status requests, returning server and resource usage information (version, connection and request counters, CPU, memory and disk usage) as JSON.
-
spa:
6A handler for single page applications: like
staticFile, but requests for files that do not exist are answered with theindex.html(orindex.htm) file of thealiasfolder (a request path without trailing/is first redirected with status code301to the same path with trailing/).
Example:
infinity.loadModule('infinity.http');
let handler = infinity.http.server.handler.custom;
infinity.http.server.protocol¶
Values:
-
tls1:
2Specifies the usage of TLS 1.0.
-
tls1_1:
3Specifies the usage of TLS 1.1.
-
tls1_2:
4Specifies the usage of TLS 1.2.
-
tls1_3:
5Specifies the usage of TLS 1.3.
Example:
infinity.loadModule('infinity.http');
let protocol = infinity.http.server.protocol.tls1_2;
cookiesArray¶
Extends: Array<{name: string, value: string, expires: number, path: string, domain: string}>
An array containing objects with cookie data inside its properties.
Properties:¶
-
name¶
Type:
string. The name of a cookie field. -
value¶
Type:
string. The value of a cookie field. -
expires¶
Type:
number. The expiration date for the cookie as timestamp in milliseconds since 1970-01-01 (UTC). -
path¶
Type:
string. The storage path for the cookie. -
domain¶
Type:
string. The domain the cookie is set from.
filesArray¶
Extends: Array<{controlName: string, fileName: string, tempFilename: string, size: number, contentType: string}>
An array containing objects with data inside its properties.
Properties:¶
-
controlName¶
Type:
string. The name of the used HTML form control. -
fileName¶
Type:
string. The name of the file. -
tempFilename¶
Type:
string. The temporary filename, the file is available under. Is only set during the actual request. -
size¶
Type:
number. The size of the file. -
contentType¶
Type:
string. The MIME-Type of the file.
formDataArray¶
Extends: Array<{fieldName: string, fileName?: string, fieldValue?: string|infinity.stream, charset?: string, contentType?: string}>
An array containing objects with data inside its properties. Depending on the given properties, each element is sent as:
- stream attachment, if
fieldValueis aninfinity.stream, - text field, if
fieldValueis a non-empty string (sent as binary field without content type if neithercharsetnorcontentTypeis given), - file attachment, if
fieldValueis not given (or empty) andfileNameis given.
Properties:¶
-
fieldName¶
Type:
string. The name of the form field (required). -
fieldValue¶
Type:
stringorinfinity.stream, optional. The value of the form field. If aninfinity.streamis used, then the form field will be a file attachment with the content being read from the stream and the filename being taken from thefileNameproperty. -
fileName¶
Type:
string, optional. The path to a file that will be transmitted in the form data (only used if nofieldValueis given). If aninfinity.streamis used asfieldValuethen the content will be read from the stream instead of the file. ThefileNamewill then just be used as the filename for the form field. -
charset¶
Type:
string, optional. The character encoding of the form field. -
contentType¶
Type:
string, optional. The MIME-Type of the form field.
headerArray¶
Extends: Array<{name: string, value: string}>
An array of objects containing name-value string pairs (HTTP-header names and values).
methodArray¶
Extends: Array<{name: string, params?: Array<string>, result?: any, rest?: string, httpEnvironment?: boolean}>
An array containing objects with data inside its properties.
Properties:¶
-
name¶
Type:
string. The name of the function. -
params¶
Type:
Array<string>, optional. The function parameters in the format'name: type'or'name?: type'(optional parameter), see registerService(). -
result¶
Type:
any, optional. The declared return type of the function result (only used for the description of theapihandler, not validated). -
rest¶
Type:
string, optional. The REST verb the function is mapped to:'get','getList','post','put'or'delete'. -
httpEnvironment¶
Type:
boolean, optional. If set to true,infinity.http.requestandinfinity.http.responseare available inside the function.
paramArray¶
Extends: Array<any>
An array of data of any type.
rangeArray¶
Extends: Array<{firstOffset: number, lastOffset: number}>
An array containing objects with data inside its properties.
Properties:¶
stringArray¶
Extends: Array<string>
An array of strings.
typesArray¶
Extends: Array<{name: string, kind: string, values?: Array<string>, properties?: Array<string>, of?: string}>
An array of custom type definitions, see registerTypes().
Properties:¶
-
name¶
Type:
string. The name of the type (e.g.'users.user'). -
kind¶
Type:
string. The kind of the type:'enum','object'or'array'. -
values¶
Type:
Array<string>, optional. Only for kind'enum': the enum values in the format'name = number'. -
properties¶
Type:
Array<string>, optional. Only for kind'object': the properties in the format'name: type'or'name?: type'(optional property). -
of¶
Type:
string, optional. Only for kind'array': the type of the array elements.
valuesArray¶
Extends: Array<{name: string, value: string}>
An array containing objects with data inside its properties.