Kiren is a lightweight JavaScript runtime built with Zig and QuickJS. This document describes the available APIs.
- Bundle Command
- Kiren Global Object
- HTTP Server
- WebSocket Server
- SQLite Database
- File System
- Path
- Process
- Buffer
- URL
- Encoding
- Crypto
- Timers
- Console
- Module System
- Compatibility Libraries
Create standalone executables from your JavaScript applications.
# Create standalone executable
kiren bundle app.js
# Specify output name
kiren bundle app.js -o myapp
# Create JS bundle only (no executable)
kiren bundle app.js --js-onlyThe bundle command:
- Parses your entry file and finds all
require()calls - Recursively bundles all local dependencies
- Creates a self-contained executable with embedded JavaScript
// app.js
const utils = require("./utils.js");
console.log("Sum:", utils.add(2, 3));
// utils.js
module.exports = {
add: function(a, b) { return a + b; }
};kiren bundle app.js -o myapp
./myapp
# Output: Sum: 5| Option | Description |
|---|---|
-o <name> |
Output file name (default: input name without .js) |
--js-only |
Create bundled JS file instead of executable |
- Only local dependencies (
./or../paths) are bundled - Built-in modules (express, axios, etc.) are available at runtime
- The output executable is self-contained and requires no external files
The Kiren object is available globally and provides core runtime functionality.
Returns the current Kiren version string.
console.log(Kiren.version); // "0.1.0"Starts an HTTP server.
Parameters:
| Name | Type | Description |
|---|---|---|
options.port |
number |
Port to listen on |
options.fetch |
function |
Request handler function |
Request object properties:
| Property | Type | Description |
|---|---|---|
method |
string |
HTTP method (GET, POST, etc.) |
url |
string |
Request URL path |
headers |
object |
Request headers |
body |
string |
Request body (for POST/PUT) |
Example:
Kiren.serve({
port: 3000,
fetch: function(req) {
if (req.url === "/") {
return new Response(JSON.stringify({ message: "Hello" }), {
status: 200,
headers: { "Content-Type": "application/json" }
});
}
return new Response("Not Found", { status: 404 });
}
});Creates an HTTP response.
Constructor:
new Response(body, options)| Parameter | Type | Description |
|---|---|---|
body |
string |
Response body |
options.status |
number |
HTTP status code |
options.headers |
object |
Response headers |
Starts a WebSocket server.
Parameters:
| Name | Type | Description |
|---|---|---|
options.port |
number |
Port to listen on |
options.open |
function |
Called when client connects |
options.message |
function |
Called when message received |
options.close |
function |
Called when client disconnects |
WebSocket object properties:
| Property | Type | Description |
|---|---|---|
ws.id |
string |
Unique client identifier |
Example:
Kiren.ws({
port: 8080,
open: function(ws) {
console.log("Connected:", ws.id);
},
message: function(ws, data) {
console.log("Received:", data);
},
close: function(ws) {
console.log("Disconnected:", ws.id);
}
});Sends a message to a specific client.
| Parameter | Type | Description |
|---|---|---|
ws |
object |
WebSocket client object |
message |
string |
Message to send |
Sends a message to all connected clients.
| Parameter | Type | Description |
|---|---|---|
message |
string |
Message to broadcast |
Adds a client to a room.
| Parameter | Type | Description |
|---|---|---|
ws |
object |
WebSocket client object |
roomId |
string |
Room identifier |
Sends a message to all clients in a room.
| Parameter | Type | Description |
|---|---|---|
roomId |
string |
Room identifier |
message |
string |
Message to broadcast |
Kiren includes native SQLite support for embedded database operations. No external dependencies required.
Opens or creates a SQLite database.
| Parameter | Type | Description |
|---|---|---|
path |
string |
Database file path, or :memory: for in-memory database |
Returns: Database object
// In-memory database
const db = Kiren.sqlite(':memory:');
// File-based database
const db = Kiren.sqlite('app.db');Executes one or more SQL statements. Use for DDL commands (CREATE, DROP, etc.) and statements that don't return data.
| Parameter | Type | Description |
|---|---|---|
sql |
string |
SQL statement(s) to execute |
db.exec('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)');
db.exec('CREATE INDEX idx_email ON users(email)');Executes a single SQL statement with optional parameters. Use for INSERT, UPDATE, DELETE operations.
| Parameter | Type | Description |
|---|---|---|
sql |
string |
SQL statement with ? placeholders |
params |
array |
Parameter values (optional) |
Returns: object with:
changes- Number of rows affectedlastInsertRowid- Last inserted row ID
const result = db.run('INSERT INTO users (name, email) VALUES (?, ?)', ['Mert', 'mert@example.com']);
console.log(result.lastInsertRowid); // 1
console.log(result.changes); // 1
db.run('UPDATE users SET name = ? WHERE id = ?', ['Mert K.', 1]);
db.run('DELETE FROM users WHERE id = ?', [1]);Executes a SELECT query and returns all matching rows.
| Parameter | Type | Description |
|---|---|---|
sql |
string |
SELECT statement with ? placeholders |
params |
array |
Parameter values (optional) |
Returns: array of row objects
// Get all users
const users = db.query('SELECT * FROM users');
// [{ id: 1, name: 'Mert', email: 'mert@example.com' }, ...]
// With parameters
const user = db.query('SELECT * FROM users WHERE id = ?', [1]);
// With conditions
const active = db.query('SELECT * FROM users WHERE age > ? AND status = ?', [18, 'active']);Closes the database connection. Always close when done to free resources.
db.close();| JavaScript Type | SQLite Type |
|---|---|
number (integer) |
INTEGER |
number (float) |
REAL |
string |
TEXT |
null / undefined |
NULL |
boolean |
INTEGER (0 or 1) |
const db = Kiren.sqlite(':memory:');
// Create tables
db.exec(`
CREATE TABLE products (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
price REAL,
stock INTEGER DEFAULT 0
)
`);
// Insert data
db.run('INSERT INTO products (name, price, stock) VALUES (?, ?, ?)', ['Laptop', 999.99, 10]);
db.run('INSERT INTO products (name, price, stock) VALUES (?, ?, ?)', ['Mouse', 29.99, 50]);
db.run('INSERT INTO products (name, price, stock) VALUES (?, ?, ?)', ['Keyboard', 79.99, 25]);
// Query data
const expensive = db.query('SELECT * FROM products WHERE price > ?', [50]);
console.log(expensive);
// [{ id: 1, name: 'Laptop', price: 999.99, stock: 10 },
// { id: 3, name: 'Keyboard', price: 79.99, stock: 25 }]
// Aggregate query
const total = db.query('SELECT COUNT(*) as count, SUM(price) as total FROM products');
console.log(total[0]); // { count: 3, total: 1109.97 }
db.close();The fs module provides synchronous file system operations. Available globally without require.
Reads a file synchronously.
| Parameter | Type | Description |
|---|---|---|
path |
string |
File path |
encoding |
string |
Encoding (e.g., "utf8") |
Returns: string - File contents
const content = fs.readFileSync("config.json", "utf8");Writes data to a file.
| Parameter | Type | Description |
|---|---|---|
path |
string |
File path |
data |
string |
Data to write |
fs.writeFileSync("output.txt", "Hello World");Checks if a file or directory exists.
| Parameter | Type | Description |
|---|---|---|
path |
string |
Path to check |
Returns: boolean
Returns file statistics.
| Parameter | Type | Description |
|---|---|---|
path |
string |
File path |
Returns: object with properties:
size- File size in bytesisFile- Whether path is a fileisDirectory- Whether path is a directory
Reads directory contents.
| Parameter | Type | Description |
|---|---|---|
path |
string |
Directory path |
Returns: array - Array of filenames
Creates a directory.
Deletes a file.
Removes a directory.
The path module provides path manipulation utilities. Available globally without require.
| Property | Description |
|---|---|
path.sep |
Path separator ("/" on POSIX) |
path.delimiter |
Path delimiter (":" on POSIX) |
Joins path segments.
path.join("/foo", "bar", "baz"); // "/foo/bar/baz"Returns the directory name.
path.dirname("/foo/bar/file.txt"); // "/foo/bar"Returns the last portion of a path.
path.basename("/foo/bar/file.txt"); // "file.txt"
path.basename("/foo/bar/file.txt", ".txt"); // "file"Returns the file extension.
path.extname("index.html"); // ".html"Normalizes a path.
path.normalize("/foo/bar//baz/../qux"); // "/foo/bar/qux"Resolves a sequence of paths to an absolute path.
path.resolve("foo", "bar"); // "/current/working/dir/foo/bar"Determines if a path is absolute.
path.isAbsolute("/foo/bar"); // true
path.isAbsolute("foo/bar"); // falseReturns an object with path components.
path.parse("/home/user/file.txt");
// { root: "/", dir: "/home/user", base: "file.txt", ext: ".txt", name: "file" }Returns a path string from an object.
The process object provides information about the current process. Available globally.
| Property | Type | Description |
|---|---|---|
process.platform |
string |
Operating system platform |
process.arch |
string |
CPU architecture |
process.pid |
number |
Process ID |
process.env |
object |
Environment variables |
process.argv |
array |
Command line arguments |
Returns the current working directory.
console.log(process.cwd()); // "/Users/user/project"Exits the process with the specified code.
process.exit(0); // Success
process.exit(1); // ErrorThe Buffer class handles binary data. Available globally.
Creates a zero-filled buffer of specified size.
const buf = Buffer.alloc(10);Creates a buffer from a string or array.
const buf1 = Buffer.from("Hello");
const buf2 = Buffer.from([72, 101, 108, 108, 111]);Concatenates an array of buffers.
const combined = Buffer.concat([buf1, buf2]);Tests if an object is a Buffer.
Returns byte length of a string or buffer.
Converts buffer to string.
Returns a new buffer that references the same memory.
Copies data to target buffer.
Writes a string to the buffer.
Fills the buffer with a value.
Compares two buffers.
Reads/writes unsigned 8-bit integer.
| Property | Type | Description |
|---|---|---|
buffer.length |
number |
Buffer size in bytes |
The URL class provides URL parsing. Available globally.
const url = new URL("https://example.com:8080/path?query=value#hash");| Property | Type | Description |
|---|---|---|
href |
string |
Full URL |
protocol |
string |
Protocol (e.g., "https:") |
hostname |
string |
Host name |
port |
string |
Port number |
pathname |
string |
Path |
search |
string |
Query string with "?" |
hash |
string |
Fragment with "#" |
origin |
string |
Origin (protocol + host) |
searchParams |
URLSearchParams |
Query parameters |
Returns the full URL string.
Handles URL query parameters. Available globally.
const params = URLSearchParams("foo=1&bar=2");Returns the first value for a parameter.
Returns all values for a parameter.
Checks if a parameter exists.
Sets a parameter value.
Appends a value to a parameter.
Removes a parameter.
Returns the query string.
Encodes strings to UTF-8 bytes.
const encoder = new TextEncoder();
const bytes = encoder.encode("Hello");| Property | Type | Description |
|---|---|---|
encoding |
string |
Always "utf-8" |
encode(string)- ReturnsUint8Array
Decodes UTF-8 bytes to strings.
const decoder = new TextDecoder();
const text = decoder.decode(bytes);| Property | Type | Description |
|---|---|---|
encoding |
string |
Always "utf-8" |
decode(buffer)- Returnsstring
The crypto object provides cryptographic functionality. Available globally.
Generates a random UUID v4.
const id = crypto.randomUUID(); // "550e8400-e29b-41d4-a716-446655440000"Fills a typed array with random values.
const arr = new Uint8Array(16);
crypto.getRandomValues(arr);Timer functions are available globally.
Executes a callback after a delay.
| Parameter | Type | Description |
|---|---|---|
callback |
function |
Function to execute |
delay |
number |
Delay in milliseconds |
Returns: number - Timer ID
Cancels a timeout.
Executes a callback repeatedly.
| Parameter | Type | Description |
|---|---|---|
callback |
function |
Function to execute |
interval |
number |
Interval in milliseconds |
Returns: number - Timer ID
Cancels an interval.
The console object provides logging functions.
Outputs a message to stdout.
Outputs a warning message.
Outputs an error message to stderr.
Kiren supports CommonJS modules.
Loads a module.
const myModule = require("./mymodule.js");
const config = require("./config.json");Exports values from a module.
// mymodule.js
module.exports = {
hello: function() { return "Hello"; }
};
// or
module.exports = function() { return "Hello"; };- Relative paths:
./module.js,../module.js - JSON files:
./config.json - lib/ directory:
require("express")loadslib/express.js
Kiren includes drop-in replacements for popular npm packages in the lib/ directory.
Express.js compatible HTTP framework.
const express = require("express");
const app = express();
app.get("/", function(req, res) {
res.json({ message: "Hello" });
});
app.post("/users", function(req, res) {
res.status(201).json(req.body);
});
app.listen(3000, function() {
console.log("Server running on port 3000");
});Supported features:
app.get(),app.post(),app.put(),app.delete()app.use()for middlewareexpress.Router()for modular routesexpress.json()body parserexpress.cors()CORS middlewareexpress.static()static file serving- Route parameters (
:id) - Query string parsing
- Cookie parsing
req.params,req.query,req.body,req.headersres.json(),res.send(),res.status(),res.set()
Serve static files from a directory:
const express = require("express");
const app = express();
// Serve files from ./public directory
app.use(express.static("./public"));
// With options
app.use(express.static("./assets", {
index: "index.html" // Default index file (set to false to disable)
}));
app.listen(3000);Options:
| Option | Type | Default | Description |
|---|---|---|---|
index |
string|false |
"index.html" |
Index file for directories |
Supported MIME types:
.html→text/html.css→text/css.js→text/javascript.json→application/json.png→image/png.jpg→image/jpeg- Other files →
application/octet-stream
Security features:
- Path traversal protection (
..blocked) - URL decoding with error handling
HTTP client for making requests.
const axios = require("axios");
// GET request
const response = axios.get("https://api.example.com/users");
console.log(response.data);
// POST request
axios.post("https://api.example.com/users", {
name: "John"
});
// With config
axios.request({
method: "GET",
url: "https://api.example.com/data",
params: { page: 1 },
headers: { "Authorization": "Bearer token" }
});Supported features:
axios.get(),axios.post(),axios.put(),axios.delete(),axios.patch()axios.create()for instances with defaults- Request config:
baseURL,headers,params,data,auth - Response object:
data,status,statusText,headers
JWT token handling.
const jwt = require("jsonwebtoken");
// Create token
const token = jwt.sign({ userId: 123 }, "secret", { expiresIn: "1h" });
// Decode token (without verification)
const decoded = jwt.decode(token);
// Verify token
const payload = jwt.verify(token, "secret");Supported features:
jwt.sign()withexpiresInoptionjwt.decode()withcompleteoptionjwt.verify()with expiration check
Environment variable loader.
require("dotenv").config();
console.log(process.env.API_KEY);Supported features:
- Loads
.envfile intoprocess.env - Custom path via
config({ path: ".env.local" }) - Comment and quote handling
UUID generation.
const { v4: uuidv4 } = require("uuid");
const id = uuidv4(); // "550e8400-e29b-41d4-a716-446655440000"Global fetch function for HTTP requests.
const response = fetch("https://api.example.com/data", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "value" })
});
const data = response.json();Request options:
| Option | Type | Description |
|---|---|---|
method |
string |
HTTP method |
headers |
object |
Request headers |
body |
string |
Request body |
Response object:
| Property/Method | Description |
|---|---|
status |
HTTP status code |
statusText |
Status message |
headers |
Response headers |
json() |
Parse body as JSON |
text() |
Get body as text |