k.module
KScript runtime API for script modules (Develop → Modules)
| Execution Context | Prerequisites | Typical Use |
|---|---|---|
| Module scripts (context members) or Site Code / API (management methods) | Context members require a Module execution context; management needs site auth | Isolated module files/DBs, scheduled tasks, ZIP & repository sync |
A module is a self-contained extension package with its own directories and routes (view/, api/, code/, module.config, etc.), mounted inside a site under /_moduleName/{part}. k.module exposes the active module context, settings, scheduled tasks, module-local files and databases, and site-level module package management (create, import, export, and repository install).
Quick Start
// Read module.config settings and write a module-local file inside a module script
const prefix = k.module.baseUrl
const title = k.module.config?.text || k.module.name
const files = k.module.openFileStream("file")
files.writeText("notes.txt", "hello from " + prefix)
const text = files.readText("notes.txt")Quick Reference
| Method / Property | Description | Returns |
|---|---|---|
baseUrl / name / config | Current module root URL, name, and saved settings (module context) | string / any |
task | Fluent scheduler API for module background tasks (module context) | KTask |
localFile / openFileStream(fileType) | Read and write files in module resource folders (module context) | LocalFile / KModuleFiles |
localIndexedDb / localSqlite | Module-local isolated databases (module context) | IDatabase / SqliteDatabase |
list() / isNameExists(name) | List site modules or check module name availability | ScriptModule[] / boolean |
createModule(name) / remove(...) | Create empty module metadata or delete a module by ID/name | ScriptModule / void |
importZip(name, binary) / exportAsZip(nameOrId) | Import or export a module archive as zip bytes | string / number[] |
importFromUrl(...) | Fetch and install a module from another Kooboo site | string |
searchRepository(keyword) / installFromRepository(packageId, name) | Search and install modules from the Kooboo repository | ModuleSearchResult[] / string |
Execution context
Context-scoped members (baseUrl, config, name, localFile, localIndexedDb, localSqlite, task, and openFileStream) are available only when executing inside a module script (module view/api/code, or an entry imported via Module: / ModuleApi:). Accessing them from ordinary site Code or API scripts throws part of k.module only available under Module execution context.
Site-level management methods (list, createModule, remove, isNameExists, importZip, exportAsZip, importFromUrl, searchRepository, installFromRepository) can be called from authorized site scripts. Create or import modules and configure module.config settings under Modules (CMS).
Difference from k.site and Module Imports
| API | Scope |
|---|---|
k.site.* | Site-wide pages, layouts, views, and Code resources |
k.module.* | Current module package files, configuration, local stores, and routing |
import { helper } from "Module:myModule/utils.js"
// Module API entry
import api from "ModuleApi:myModule/hello.js"Module: automatically resolves inside the module's code/ directory and ModuleApi: resolves inside api/. Provide the exact relative filename including extension (no .js extension is appended automatically, and do not duplicate code/ or api/ in the specifier).
Module-Context Members
baseUrl / config / name
Read the active module's root URL (including its route prefix, without a trailing slash /, e.g. https://example.com/_myModule), saved admin settings (from settingDefines in module.config plus site settings JSON), and active module name.
Note: On the first read when module settings have not yet been initialized in the database, k.module.config persists default values from module.config and returns null (subsequent reads return the parsed settings object). Always guard property reads with optional chaining such as k.module.config?.text.
Returns: baseUrl and name return string; config returns Record<string, any> | null.
// Inside module view or api scripts
const home = k.module.baseUrl + "/index"
const title = k.module.config?.text
const moduleName = k.module.nametask
Fluent scheduler API for module background tasks (typically placed in event.js or a task script).
| Method | Parameters | Returns | Description |
|---|---|---|---|
day(day) | day: number | KTask | Set day interval |
hour(hour) | hour: number | KTask | Set hour interval |
minute(minutes) | minutes: number | KTask | Set minute interval |
run(js) | js: any | void | Register the callback function to run on schedule |
Returns: day, hour, and minute return KTask for chaining; run returns void.
k.module.task
.day(1)
.hour(0)
.run(function () {
// scheduled logic
})localFile / openFileStream()
Access files inside the module's directory on disk, grouped by resource directory, or call k.module.openFileStream(fileType) where fileType is one of css, js, view, api, img, or file.
| Member | Directory |
|---|---|
k.module.localFile.view | view/ |
k.module.localFile.api | api/ |
k.module.localFile.js | js/ |
k.module.localFile.css | css/ |
k.module.localFile.img | img/ |
k.module.localFile.file | file/ |
KModuleFiles methods:
| Method | Parameters | Returns | Description |
|---|---|---|---|
readText(fileName) | fileName: string | string | Read a text file |
writeText(fileName, content) | fileName: string, content: string | void | Write a text file |
readBytes(fileName) | fileName: string | number[] | Read binary bytes |
writeBytes(fileName, binaryBytes) | fileName: string, binaryBytes: number[] | void | Write binary bytes |
delete(fileName) | fileName: string | void | Delete a file |
files() | None | ModuleFileInfo[] | List files in that resource directory |
Returns: openFileStream() returns KModuleFiles.
// Inside a module script, read and write in file/
const files = k.module.openFileStream("file")
files.writeText("notes.txt", "hello module")
const text = files.readText("notes.txt")
const entries = files.files()localIndexedDb / localSqlite
| Member | Description |
|---|---|
k.module.localIndexedDb | Module-local IndexedDB-style database (IDatabase) |
k.module.localSqlite | Module-local SQLite database (_sqlite.db at module root) |
Ideal for module-private storage, isolated from the site's k.DB.
Site-Level Management APIs
These methods run in authorized site Code / API scripts to automate module installation and lifecycle operations.
list()
Return all ScriptModule records registered in the site.
Parameters: None.
Returns: ScriptModule[].
k.api.get(() => {
return k.module.list().map((m) => ({ id: m.id, name: m.name, online: m.online }))
})createModule()
Create a new ScriptModule metadata entry and register its module route. Note that createModule() only saves the module metadata without creating its folder on disk until files are created inside it (calling exportAsZip() immediately on an empty newly created module throws a missing-directory error).
| Parameter | Type | Required | Description |
|---|---|---|---|
name | string | Yes | New module name |
Returns: ScriptModule.
k.api.post(() => {
const mod = k.module.createModule(k.request.form.name)
return { id: mod.id, name: mod.name }
})remove()
Delete a module by GUID Id, name/ID string, or on a remote destination site domain.
| Overload | Description |
|---|---|
remove(Id) | Delete module in the current site by GUID |
remove(IdOrName) | Delete module in the current site by ID or name |
remove(IdOrName, DestinationSiteUrl) | Delete matching module on the specified destination site URL |
| Parameter | Type | Required | Description |
|---|---|---|---|
Id / IdOrName | any | string | Yes | Module ID or name |
DestinationSiteUrl | string | No | Target site domain (omit to target current site) |
Returns: void.
k.api.post(() => {
k.module.remove(k.request.form.name)
return { ok: true }
})isNameExists()
Check whether a module name already exists in the current site.
| Parameter | Type | Required | Description |
|---|---|---|---|
name | string | Yes | Module name to check |
Returns: boolean.
k.api.get(() => {
return { exists: k.module.isNameExists(k.request.queryString.name) }
})importZip()
Create a module and extract a zip archive into its directory, returning the new module ID.
| Parameter | Type | Required | Description |
|---|---|---|---|
name | string | Yes | Imported module name |
binary | number[] | Yes | Zip file byte array |
Returns: string. New module ID.
k.api.post(() => {
const file = k.request.files[0]
const id = k.module.importZip(k.request.form.name, file.bytes)
return { id }
})exportAsZip()
Export an existing module directory as a zip byte array, or null if the module does not exist.
| Parameter | Type | Required | Description |
|---|---|---|---|
nameOrId | string | Yes | Module name or ID |
Returns: number[] | null.
k.api.get(() => {
const bytes = k.module.exportAsZip(k.request.queryString.name)
return { size: bytes ? bytes.length : 0 }
})importFromUrl()
Fetch a shared module zip from another Kooboo site and install it.
| Overload | Description |
|---|---|
importFromUrl(SiteUrl, ModuleId, newModuleName) | Install into current site (ModuleId accepts string or GUID) |
importFromUrl(SiteUrl, ModuleId, newModuleName, DestinationSiteUrl) | Install into a target site |
| Parameter | Type | Required | Description |
|---|---|---|---|
SiteUrl | string | Yes | Source site URL |
ModuleId | string | any | Yes | Source module GUID |
newModuleName | string | Yes | Installed module name |
DestinationSiteUrl | string | No | Target site URL (omit for current site) |
Returns: string. Installed module ID.
k.api.post(() => {
const id = k.module.importFromUrl(
k.request.form.siteUrl,
k.request.form.moduleId,
k.request.form.name
)
return { id }
})searchRepository() / installFromRepository()
Search the Kooboo module repository and install a package by packageId.
| Method | Parameters | Returns | Description |
|---|---|---|---|
searchRepository(keyword) | keyword: string | ModuleSearchResult[] | Search packages by keyword |
installFromRepository(packageId, name) | packageId: string, name: string | string | Install package and return module ID |
Returns: searchRepository() returns ModuleSearchResult[]; installFromRepository() returns the new module ID string.
k.api.post(() => {
const results = k.module.searchRepository(k.request.form.keyword)
if (!results.length) return { installed: false }
const id = k.module.installFromRepository(results[0].packageId, k.request.form.name)
return { installed: true, id }
})module.config Conventions
Common fields in a module's root module.config JSON file:
| Field | Description |
|---|---|
name / version / description | Package metadata (name serves as the menu module identifier) |
settingDefines | Form definitions for admin Settings (name, type, defaultValue, display, etc.) |
menu | Admin sidebar entry configuration (applies only to online modules) |
Menu Configuration
When a site loads, Kooboo reads menu entries from online modules' module.config files and merges them into the admin left navigation (see Modules (CMS)).
| Field | Description |
|---|---|
name | Menu title |
nameTranslation | Optional localized titles keyed by admin user language |
parent | Optional parent top-level menu key (such as commerce or content) |
url | Optional relative path under module view/ (defaults to module start view when empty) |
icon | Optional image file name under img/ |
children | Optional submenu items containing name, url, etc. |
Resolved URLs follow /_moduleName/{viewPath}?SiteId={siteGuid}. Saved settingDefines values are exposed to module scripts via k.module.config. Module documentation can live in Readme.md.
TypeScript Definitions
Show full TypeScript definitions
interface KModule {
task: KTask;
baseUrl: string;
config: any;
name: string;
localIndexedDb: IDatabase;
localSqlite: SqliteDatabase;
localFile: LocalFile;
list(): ScriptModule[];
createModule(name: string): ScriptModule;
remove(Id: any): void;
remove(IdOrName: string): void;
remove(IdOrName: string, DestinationSiteUrl: string): void;
isNameExists(name: string): boolean;
importZip(name: string, Binary: number[]): string;
exportAsZip(NameOrId: string): number[];
importFromUrl(SiteUrl: string, ModuleId: string, newModuleName: string): string;
importFromUrl(SiteUrl: string, ModuleId: any, newModuleName: string): string;
importFromUrl(SiteUrl: string, ModuleId: string, newModuleName: string, DestinationSiteUrl: string): string;
searchRepository(keyword: string): ModuleSearchResult[];
installFromRepository(PackageId: string, Name: string): string;
openFileStream(fileType: string): KModuleFiles;
}
interface LocalFile {
css: KModuleFiles;
js: KModuleFiles;
api: KModuleFiles;
img: KModuleFiles;
file: KModuleFiles;
view: KModuleFiles;
}
interface KModuleFiles {
context: any;
type: any;
readText(FileName: string): string;
writeText(fileName: string, content: string): void;
readBytes(FileName: string): number[];
writeBytes(fileName: string, BinaryBytes: number[]): void;
delete(fileName: string): void;
files(): ModuleFileInfo[];
}
interface ModuleFileInfo {
name: string;
fullName: string;
folderName: string;
extension: string;
size: number;
stringSize: string;
lastModified: Date;
}
interface KTask {
hour(hour: number): KTask;
minute(minutes: number): KTask;
day(day: number): KTask;
run(js: any): void;
}
interface ScriptModule {
id: any;
name: string;
packageName: string;
moduleVersion: string;
relativeFolder: string;
startView: string;
settings: string;
taskJs: string;
online: boolean;
creationDate: Date;
lastModified: Date;
}
interface ModuleSearchResult {
packageId: string;
title: string;
description: string;
}Related Docs
- Modules (CMS) — List, import, development mode, online status, and sharing
- k.site — Site resources
- k.DB — Site databases
- k.file — Site files outside module directories
- Scheduled Jobs — Site-level scheduled jobs