INFINITY.JS Quick Reference Card¶
A concise reference for common INFINITY.JS operations and patterns.
Project Setup¶
Basic Project Structure¶
bin/
win-x64/ # Runtime for Windows x64
linux-x64/ # Runtime for Linux x64
resources/ # infinity.d.ts (type definitions)
my-app/ # Your project, next to the platform folders
ts/ # TypeScript source files
main.ts # Entry point
services/ # Service modules
js/ # Compiled JavaScript (output)
web/ # Static web content (optional)
tsconfig.json # TypeScript configuration
TypeScript Configuration (tsconfig.json)¶
{
"compilerOptions": {
"target": "es5",
"lib": ["es5"],
"module": "none",
"types": [],
"outDir": "js/",
"emitBOM": true,
"sourceMap": true
},
"include": [
"../resources/infinity.d.ts",
"ts/**/*"
]
}
The infinity.d.ts path depends on the folder depth: ../resources/infinity.d.ts for bin/my-app, ../../resources/infinity.d.ts for bin/examples/<name>.
Running Your Application¶
# Relative script paths are resolved against the folder of the executable
# Windows
bin\win-x64\infinity.exe -console ../my-app/js/main.js
# Linux
bin/linux-x64/infinity -console ../my-app/js/main.js
# With remote debugger (default port 9090, start paused)
infinity -console -debug -port 9090 -paused ../my-app/js/main.js
# List modules / show help and version
infinity -listModules
infinity -help
| Option | Description |
|---|---|
-console | Run as console application with standard output |
-interactive | Interactive mode (JavaScript shell) |
-listModules | List all available runtime modules and extensions |
-debug | Start with the remote debug server (also disables the script cache) |
-port <n> | Debugger TCP port (default 9090, value as separate argument: -port 9091) |
-paused | Start the debugger paused |
-disableScriptCache | Reload modified script files from disk |
-disableOpcodeCache | Disable bytecode caching |
-disableLogFile | No log file output |
-disableHeader | No startup header |
-reportMemoryLeaks | Report memory leaks on exit (Windows) |
-help, -h, -? | Show help |
Core Runtime¶
Module Loading¶
infinity.loadModule('infinity.http');
infinity.loadModule('infinity.database');
infinity.loadModule('infinity.crypto');
infinity.loadModule('infinity.fileSystem');
Always available without loadModule(): console, infinity.include(), infinity.sleep(), infinity.terminated, infinity.current, infinity.os, infinity.event, infinity.lock, infinity.encoding and infinity.fileMode. See the API reference for the module of each namespace.
File Inclusion¶
// Include compiled JavaScript files (paths relative to the main program folder)
infinity.include('core/database.js');
infinity.include('services/users.js');
Runtime Control¶
// Check termination flag
while (!infinity.terminated) {
infinity.event.processQueue(); // Process queued events
infinity.sleep(25); // Sleep 25ms
}
// Terminate application (optional exit code of the process)
infinity.terminate();
infinity.terminate(1);
// Runtime version, e.g. "3.21.316"
console.info('Version: ' + infinity.version);
// Garbage collection
infinity.gc();
// Execute pending calls from threads in the main thread,
// e.g. the onTerminated callback of infinity.thread (main thread only)
infinity.processEvents();
Important Paths¶
infinity.current.run // Folder of the INFINITY.JS executable
infinity.current.root // Main program folder
infinity.current.temp // Temp folder
infinity.current.dir // Folder of the currently executed script
infinity.current.file // File name of the currently executed script
File Operations¶
File Operations¶
infinity.loadModule('infinity.fileSystem');
// Check existence
infinity.file.exists('data.txt')
// Read file
let content = infinity.file.readString('data.txt', infinity.encoding.utf8);
// Write file
infinity.file.writeString('data.txt', 'content', infinity.encoding.utf8);
// Copy, move, delete
infinity.file.copy('src.txt', 'dst.txt');
infinity.file.move('old.txt', 'new.txt');
infinity.file.remove('file.txt');
Directory Operations¶
// List files
let files = infinity.directory.list('./', '*.txt', infinity.directory.filter.files);
// Create/remove directory
infinity.directory.create('newdir');
infinity.directory.remove('olddir', true); // recursive
Path Utilities¶
// Extract directory from path
let dir = infinity.fileName.extractDirectory('C:/path/to/file.txt');
// Extract filename
let name = infinity.fileName.extract('C:/path/to/file.txt', true); // strip extension
// Get extension
let ext = infinity.fileName.extension('file.txt');
// Expand relative path
let full = infinity.fileName.expand('../relative/path.txt');
Note
Relative file paths in the file system functions are resolved against the folder of the executable (the current directory of the process). Use infinity.current.root to build paths relative to your main program, e.g. infinity.current.root + '../data.txt'.
HTTP Server¶
Basic Server Setup¶
infinity.loadModule('infinity.http');
let server = new infinity.http.server(
true, // SSL
false, // Verify certificate
true, // Allow CORS
true, // Compress
true, // Access log
443, // Port
1024, // Max connections
64, // Pool size
104857600, // Max content length (100MB)
5.0 // Slow request time (seconds)
);
// Own certificate (default: test certificate resources/infinity.crt + infinity.key)
server.setCertificate(infinity.current.root + '../cert/server.crt', infinity.current.root + '../cert/server.key');
// Static files
server.registerHandler(infinity.http.server.handler.staticFile, '/', '../web/');
// REST API
server.registerHandler(infinity.http.server.handler.rest, '/api/v1/rest');
// JSON-RPC
server.registerHandler(infinity.http.server.handler.jsonRpc, '/api/v1/json');
server.start();
Type Definitions¶
// Register custom types
server.registerTypes([
// Enum
{name: 'users.role', kind: 'enum', values: ['user = 1', 'admin = 2']},
// Object with validation
{name: 'users.user', kind: 'object', properties: [
'id: number{0,}', // Non-negative
'username: string{3,32}', // 3-32 chars
'email: string{5,255}', // Email length
'role?: users.role' // Optional enum
]},
// Array
{name: 'users.userList', kind: 'array', of: 'users.user'}
]);
Service Registration¶
server.registerService('users', 'users', 'services/users.js', [
{
name: 'login',
params: ['username: string{3,32}', 'password: string{8,}'],
result: 'object'
},
{
name: 'get',
params: ['id: number{1,}'],
result: 'users.user',
rest: 'get'
},
{
name: 'add',
params: ['user: users.user'],
result: 'number',
rest: 'post'
}
]);
Request/Response Access¶
// In service methods with httpEnvironment: true
function upload(filename: string) {
// Request data
let contentType = infinity.http.request.contentType;
let files = infinity.http.request.files;
let cookies = infinity.http.request.cookies;
// Response
infinity.http.response.code = 200;
infinity.http.response.contentType = 'application/json';
infinity.http.response.cookies.push({name: 'theme', value: 'dark', expires: Date.now() + 86400000, path: '/', domain: ''});
}
HTTP Client¶
infinity.loadModule('infinity.http');
let client = new infinity.http.client();
client.timeout = 30000;
client.userAgent = 'MyApp/1.0';
// GET request
let response = client.get('https://api.example.com/data');
// POST JSON
client.contentType = 'application/json';
let result = client.post('https://api.example.com/users',
JSON.stringify({name: 'John'}));
// Download file
client.getFile('https://example.com/file.zip', 'download.zip');
client.free();
Database Operations¶
Connection¶
infinity.loadModule('infinity.database');
let db = new infinity.database();
try {
// SQLite
db.specificOptions['Direct'] = true;
db.specificOptions['UseUnicode'] = true;
db.specificOptions['ForceCreateDatabase'] = true;
db.connect(infinity.database.provider.sqlite, '', 0, infinity.current.root + '../database.db');
// MySQL / MariaDB
// db.connect(infinity.database.provider.mysql, 'localhost', 3306, 'dbname', 'user', 'pass');
// PostgreSQL
// db.connect(infinity.database.provider.postgresql, 'localhost', 5432, 'dbname', 'user', 'pass');
// SQL Server
// db.connect(infinity.database.provider.sqlserver, 'localhost', 1433, 'dbname', 'user', 'pass');
// Connection pooling (set before connect)
// db.pooling = true;
// db.minPoolSize = 5;
// db.maxPoolSize = 20;
// ... queries ...
db.disconnect();
} finally {
db.free();
}
Queries¶
// Simple query
db.execute('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)');
// Parameterized query (prevents SQL injection!)
db.sql = 'SELECT * FROM users WHERE id = :id AND name = :name';
db.setParamValue('id', 1);
db.setParamValue('name', 'John');
// Fetch results
if (db.execute()) {
while (!db.eof()) {
let id = db.result('id');
let name = db.result('name');
console.log(id + ': ' + name);
db.next();
}
}
// Current row as object
let user = db.rowObject();
Transactions¶
db.startTransaction(infinity.database.isolationLevel.readCommitted);
try {
db.execute('UPDATE accounts SET balance = balance - 100 WHERE id = 1');
db.execute('UPDATE accounts SET balance = balance + 100 WHERE id = 2');
db.commit();
} catch (e) {
db.rollback();
throw e;
}
NoSQL Operations¶
infinity.loadModule('infinity.noSql');
// Create collection
infinity.noSql.create('users');
// Insert
let id = infinity.noSql.insert('users', {
username: 'john',
email: 'john@example.com',
age: 30
});
// Find
let results = infinity.noSql.find('users',
[['age', '>=', 18]], // Query
'username', // Order by
infinity.noSql.orderDirection.ascending,
0, // Offset
10 // Limit
);
// Update
infinity.noSql.update('users', id, {age: 31});
// Get by ID
let user = infinity.noSql.get('users', id);
// Remove
infinity.noSql.remove('users', id);
Cryptography¶
Hashing¶
infinity.loadModule('infinity.crypto');
// MD5
let md5 = infinity.md5.hash('text', infinity.crypto.outputFormat.hex);
// SHA-256
let sha256 = infinity.sha256.hash('text', infinity.crypto.outputFormat.hex);
// SHA-512
let sha512 = infinity.sha512.hash('text', infinity.crypto.outputFormat.hex);
// HMAC
let hmac = infinity.sha256.hmac('text', 'secret-key', infinity.crypto.outputFormat.hex);
Password Hashing¶
// Hash password (bcrypt)
let hash = infinity.bcrypt.hash('password123', 10); // cost factor
// Verify password
let valid = infinity.bcrypt.verify('password123', hash);
Encryption¶
// AES-256
let encrypted = infinity.aes256.encrypt('secret data', 'password');
let decrypted = infinity.aes256.decrypt(encrypted, 'password');
// RSA
let keys = infinity.rsa.generateKeys(2048);
let rsaEncrypted = infinity.rsa.encrypt('data', keys.public);
let rsaDecrypted = infinity.rsa.decrypt(rsaEncrypted, keys.private);
// Digital signature
let signature = infinity.rsa.hashAndSign('data', keys.private,
infinity.crypto.algorithm.sha256);
let signatureValid = infinity.rsa.hashAndVerify('data', keys.public, signature,
infinity.crypto.algorithm.sha256);
// Random values
let token = infinity.random.characters(32);
Encoding¶
infinity.loadModule('infinity.encoding');
// Base64
let encoded = infinity.base64.encode('text', infinity.encoding.utf8);
let decoded = infinity.base64.decode(encoded, infinity.encoding.utf8);
// URL encoding
let urlEncoded = infinity.url.encode('text with spaces');
let urlDecoded = infinity.url.decode(urlEncoded);
// Hex
let hex = infinity.hex.encode('text');
let text = infinity.hex.decode(hex);
Multi-Threading¶
Creating Threads¶
infinity.loadModule('infinity.thread');
// Script path relative to the main program folder
let thread = new infinity.thread('worker.js',
infinity.thread.priority.normal,
// Executed in the main thread after the thread has finished
function(result: any, error: string): void {
if (error)
console.error('Thread error: ' + error);
else
console.info('Thread finished: ' + JSON.stringify(result));
}
);
thread.start();
// Wait for completion or terminate
while (!infinity.terminated && !thread.terminated) {
infinity.processEvents(); // Runs the callback (main thread only)
infinity.sleep(100);
}
thread.stop(); // Sets infinity.threadTerminated in the thread and waits for it
Thread Script (worker.js)¶
infinity.loadModule('infinity.thread'); // Needed for infinity.thread.result
// Check thread termination
while (!infinity.terminated && !infinity.threadTerminated) {
// Do work
infinity.sleep(100);
}
// Set result
infinity.thread.result = {status: 'completed', data: 123};
Shared Memory¶
infinity.loadModule('infinity.memory');
// Store data (thread-safe)
infinity.memory.putString('cache', 'key1', 'value');
infinity.memory.putNumber('cache', 'counter', 42);
infinity.memory.putBoolean('cache', 'flag', true);
infinity.memory.put('cache', 'user', {id: 1, name: 'John'});
// Retrieve data
let value = infinity.memory.getString('cache', 'key1');
let counter = infinity.memory.getNumber('cache', 'counter');
let user = infinity.memory.get('cache', 'user');
// Atomic operations
infinity.memory.increment('cache', 'counter', 1);
infinity.memory.decrement('cache', 'counter', 1);
// Check existence
if (infinity.memory.exists('cache', 'key1')) {
// Key exists
}
// Remove
infinity.memory.remove('cache', 'key1');
infinity.memory.clear('cache'); // Clear namespace
Locks (Read/Write)¶
// infinity.lock is always available (no loadModule needed)
// Locks block until they are acquired (no timeout) - don't nest locks with the same name
// Read lock (multiple readers allowed under Windows, exclusive under Linux)
infinity.lock.beginRead('resource');
try {
let value = infinity.memory.getNumber('data', 'value');
console.log(value);
} finally {
infinity.lock.endRead('resource');
}
// Write lock (exclusive)
if (infinity.lock.beginWrite('resource')) {
try {
let value = infinity.memory.getNumber('data', 'value');
infinity.memory.putNumber('data', 'value', value + 1);
} finally {
infinity.lock.endWrite('resource');
}
}
Events¶
// infinity.event is always available (no loadModule needed)
// Register event handler (one handler per event name and script)
infinity.event.register('dataUpdated', function(params: any): void {
console.log('Data updated: ' + JSON.stringify(params));
});
// Send event
infinity.event.send('dataUpdated', {id: 1, value: 'new data'});
// Process event queue
infinity.event.processQueue();
// Unregister
infinity.event.unregister('dataUpdated');
Session Management¶
Sessions¶
infinity.loadModule('infinity.session');
infinity.loadModule('infinity.crypto'); // for infinity.random
// Configure
infinity.session.secret = 'your-secret-key';
infinity.session.expires = 3600; // 1 hour in seconds
// Create session (in a request script) - the data object needs a non-empty "id" string
let sessionData = {
id: infinity.random.characters(32),
userId: 1,
username: 'john',
role: 'admin'
};
let token = infinity.session.start(sessionData,
infinity.session.algorithm.hs256); // returns a JWT
// Without algorithm: start(sessionData) sets the session cookie and returns the session id
// Get session (from cookie/token)
let session: any = infinity.session.get(infinity.session.algorithm.hs256);
if (session) {
console.log('User: ' + session.username);
// Update session
session.lastActivity = Date.now();
infinity.session.put(session);
}
// Remove session
infinity.session.remove(sessionData.id);
Email¶
Send Email (SMTP)¶
infinity.loadModule('infinity.smtp');
let smtp = new infinity.smtp.client();
smtp.host = 'smtp.example.com';
smtp.port = 587;
smtp.username = 'user@example.com';
smtp.password = 'password';
smtp.authMode = infinity.smtp.client.authMode.sasl;
smtp.encryptMode = infinity.smtp.client.encryptMode.sslTls;
// Create mail
infinity.loadModule('infinity.mail');
let mail = new infinity.mail();
mail.from = 'sender@example.com';
mail.recipients = ['recipient@example.com'];
mail.subject = 'Test Email';
mail.contents = [{contentType: 'text/plain', contentTransferEncoding: infinity.mail.transferEncoding.quotedPrintable,
charset: 'utf-8', text: 'Hello World!', items: []}];
smtp.connect();
smtp.sendMail(mail);
smtp.disconnect();
smtp.free();
mail.free();
Data Processing¶
JSON¶
// Parse
let obj = JSON.parse('{"name":"John","age":30}');
// Stringify
let json = JSON.stringify({name: 'John', age: 30});
XML¶
infinity.loadModule('infinity.xml');
// Parse XML
let obj = infinity.xml.parse('<root><item>value</item></root>');
// Generate XML
let xml = infinity.xml.stringify({root: {item: 'value'}});
Regular Expressions¶
infinity.loadModule('infinity.regEx');
// Test for a match (returns boolean)
let found = infinity.regEx.match('\\d+', 'test 123',
[infinity.regEx.option.caseLess]);
// Replace
let result = infinity.regEx.replace('\\d+', 'test 123', 'XXX');
// List all matches with groups
let matches = infinity.regEx.matchList('(\\w+)@(\\w+\\.\\w+)',
'user@example.com');
Template Engine¶
infinity.loadModule('infinity.template');
let tmpl = new infinity.template(infinity.current.root + '../templates/');
try {
tmpl.loadFromFile('page.html');
tmpl.vars['title'] = 'My Page';
tmpl.vars['users'] = [{name: 'John'}, {name: 'Jane'}];
let html = tmpl.render();
} finally {
tmpl.free();
}
Utilities¶
Date/Time¶
infinity.loadModule('infinity.date');
// Current timestamp
let now = infinity.date.now('Europe/Berlin');
// Format date
let formatted = infinity.date.formatLocal('dd.mm.yyyy hh:nn:ss', now);
// Time zones
let zones = infinity.date.listTimeZones();
// Convert between zones
let utcNow = Date.now();
let local = infinity.date.toLocalTime('America/New_York', utcNow);
let utc = infinity.date.toUniversalTime('America/New_York', local);
Compression¶
infinity.loadModule('infinity.zip');
// ZIP file
let zip = new infinity.zip.file();
zip.open('archive.zip', infinity.zip.file.mode.write);
zip.add('local-file.txt', 'archive-name.txt');
zip.close();
zip.free();
// ZLIB
infinity.loadModule('infinity.zlib');
let compressed = infinity.zlib.compress('data');
let extracted = infinity.zlib.extract(compressed);
Image Processing¶
infinity.loadModule('infinity.image');
let img = new infinity.image();
img.loadFromFile('photo.jpg');
// Resize
img.rescale(800, 600, infinity.image.filter.lanczos3);
// Rotate
img.rotate(90);
// Convert
img.convertTo24Bits();
img.saveToFile('output.jpg', infinity.image.flag.jpeg_qualitygood);
img.free();
PDF¶
infinity.loadModule('infinity.pdf');
let pdf = new infinity.pdf();
pdf.loadFromFile('document.pdf');
console.log('Pages: ' + pdf.pageCount);
// Extract text
let text = pdf.text;
// Render page to image
pdf.pageNumber = 1;
pdf.renderPage('page1.jpg', 0, 0, 800, 1000);
pdf.free();
Process Execution¶
infinity.loadModule('infinity.process');
let result = infinity.process.start(
'program.exe',
'arg1 arg2',
true, // Wait for completion
30000 // Timeout (ms)
);
if (result.success) {
console.log('Output: ' + result.output);
console.log('Exit code: ' + result.exitCode);
} else {
console.error('Error: ' + result.error);
}
Validation Syntax Reference¶
Number Constraints¶
'id: number' // Any number
'id: number{0,}' // Non-negative (>= 0)
'id: number{1,}' // Positive (>= 1)
'age: number{0,150}' // Range 0-150
'score: number{,100}' // Maximum 100
String Constraints¶
'name: string' // Any string
'name: string{1,}' // Non-empty
'username: string{3,32}' // Length 3-32
'email: string{5,255}' // Length 5-255
'code: string{6,6}' // Exactly 6 chars
Optional Properties¶
'email?: string{5,255}' // Optional email
'age?: number{0,150}' // Optional age
'role?: users.role' // Optional enum
Custom Types¶
'user: users.user' // Custom object type
'role: users.role' // Custom enum type
'ids: users.idList' // Custom array type
Best Practices¶
Resource Management¶
// Always free objects with free() method
let database = new infinity.database();
try {
// Use database
} finally {
database.free(); // Ensures cleanup
}
SQL Injection Prevention¶
// NEVER do this:
db.execute('SELECT * FROM users WHERE id = ' + userId); // UNSAFE!
// ALWAYS use parameterized queries:
db.sql = 'SELECT * FROM users WHERE id = :id';
db.setParamValue('id', userId);
db.execute();
Thread Safety¶
// Use locks for shared data
infinity.lock.beginWrite('resource');
try {
// Modify shared data
} finally {
infinity.lock.endWrite('resource');
}
Error Handling¶
let database = new infinity.database();
try {
// Operations that might fail
database.specificOptions['Direct'] = true;
database.connect(infinity.database.provider.sqlite, '', 0, infinity.current.root + '../database.db');
database.execute('DELETE FROM sessions');
database.disconnect();
} catch (error) {
console.error('Database error: ' + error);
// Handle error appropriately
} finally {
// Cleanup
database.free();
}
Graceful Termination¶
server.start();
try {
// Main loop pattern
while (!infinity.terminated) {
infinity.event.processQueue();
infinity.sleep(25); // Short sleep intervals
}
} finally {
// Cleanup on exit
server.stop();
}
Common Patterns¶
HTTP Server with Database¶
infinity.loadModule('infinity.http');
infinity.loadModule('infinity.database');
let server = new infinity.http.server(false, false, true, false, false, 8080);
server.registerHandler(infinity.http.server.handler.rest, '/api');
server.registerService('users', 'users', 'services/users.js', [
{name: 'list', result: 'array'},
{name: 'get', params: ['id: number{1,}'], result: 'object'}
]);
server.start();
try {
while (!infinity.terminated) {
infinity.event.processQueue();
infinity.sleep(25);
}
} finally {
server.stop();
}
Scheduled Tasks¶
infinity.loadModule('infinity.scheduler');
let scheduler = new infinity.scheduler();
// Plan format: minute hour day month weekday year seconds limit
// '0 3' -> every day at 3:00
// '* * * * * * */10' -> every 10 seconds
scheduler.add('backup', '0 3', 'tasks/backup.js',
infinity.scheduler.priority.normal);
while (!infinity.terminated) {
scheduler.processTasks();
infinity.sleep(250);
}
scheduler.free();
Full-Text Search¶
infinity.loadModule('infinity.fts');
// Open index
infinity.fts.open('documents');
// Add documents
infinity.fts.add('documents', 1, {
title: 'Document Title',
content: 'Document content text...'
});
// Search (max. 10 results)
let results = infinity.fts.find('documents', 'search terms', 10);
for (let i = 0; i < results.length; i++) {
console.log('ID: ' + results[i].id + ', relevance: ' + results[i].relevance);
}
infinity.fts.close('documents');
Vector Search (AI/ML)¶
infinity.loadModule('infinity.vectordb');
// Open database
infinity.vectordb.open(
'embeddings', // namespace
384, // dimensions
100000, // max items
2, // parallel threads
0.3, // compact threshold
true, // normalize
infinity.vectordb.deleteStrategy.firstId,
true, // enable IVF
100, // IVF clusters
5 // IVF probe
);
// Add vector (an array with 384 numbers, e.g. from an embedding model)
infinity.vectordb.add('embeddings', 1, embedding);
// Search similar (minimum similarity 0.7, max. 10 results)
let results = infinity.vectordb.search('embeddings', queryVector, 0.7, 10);
Additional Resources¶
- Full API Documentation: api/index.md
- Getting Started Guide: getting-started/index.md
- Server Example Tutorial: example/index.md
- Concepts: concepts/index.md
- Type Definitions:
bin/resources/infinity.d.tsin the release archive - Examples:
bin/examples/in the release archive - Downloads: GitHub releases
For detailed documentation on any topic, refer to the full API reference.