KJSutils

Quick rating

KJSutils

No reviews yet

Extend the functionality of KubeJS

Mod Loaders
NeoForge
Minecraft

Community voices

Reviews

Versions
Loading versions…
Match includes

Click once to include, again to exclude, again to clear

Rating Any
Any 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0
Min
Max
Play Status
Reviews
Time Played
hrs+
Verified developers only
Has developer response
List view
Grid view
Compact view
Sort by
Date
Rating
Helpful
Unhelpful
Edited
Sort ascending
Delete this review?

This removes your review from the project. You can write a new review after.

Review submitted for moderation

Your review has been sent to moderators, who will check that it meets our guidelines before it appears publicly.

No reviews yet. Be the first to review this project!

Get it on

Available Platforms

About

Project Details

Type
Mod
Latest Version
kjsutils-2.0.4.jar
Authors

For authors

Embed Badge

If you're the author of this project, you can embed a live badge anywhere that supports HTML or Markdown. It updates automatically whenever ratings change.

Custom banner text
ModDex rating badge preview

Use HTML for any page that supports it, or Markdown for README files and Markdown-based descriptions.

Identifiers

Platform IDs

CurseForge ID

Resources

External Links

Source Issues Wiki Discord

About

Description

KJS Utils

Simplified Chinese | English

KJS Utils is extension mod for KubeJS. It provides file operations within the game instance, JSON value extraction, HTTP file downloads, and optional FancyMenu user-variable integration.

The file and network APIs can modify files in the game instance. Only run trusted scripts, and never pass unvalidated user input directly as a path or URL.

Compatibility

Component Version Requirement
Minecraft 1.21.1 This is the only supported Minecraft version
Java 21 Required at runtime and for building
NeoForge 21.1.242 or newer Required
KubeJS 2101.7.2-build.368 or newer Required
FancyMenu 3.9.8 or newer Optional; only required for the client integration

Installation

  1. Install NeoForge and KubeJS for Minecraft 1.21.1.
  2. Put the KJS Utils JAR in the game instance's mods directory.
  3. To use KJSutilsClient, also install FancyMenu and its dependencies on the client.

Script Scope

Global object Available in Requirement
KJSutilsCommon startup_scripts, server_scripts, and client_scripts KubeJS
KJSutilsClient client_scripts only FancyMenu loaded on the client
Global object Available in Requirement
KJSUtilsEvents.playerLeftDimension server_scripts only KubeJS
KJSUtilsEvents.playerEnteredDimension server_scripts only KubeJS

When FancyMenu is not installed, KJSutilsClient is not registered. All method names are case-sensitive.

Path Rules

The path parameters in KJSutilsCommon will all:

  • resolved relative to the game directory;
  • normalized to process ., .., and path separators;
  • rejected with an IllegalArgumentException if the normalized path is outside the game directory.

Use getGamePath() to obtain the absolute game-directory path. The path check is lexical and does not resolve symbolic links, so paths must not be controlled by untrusted input.

Common Method

File Operations

Method Returns Behavior
getGamePath() string Returns the absolute game-directory path
existPath(path) boolean Returns true when a file or directory exists
isFile(path) boolean Tests for a regular file; throws NoSuchFileException when the path does not exist
isDirectory(path) boolean Tests for a directory; throws NoSuchFileException when the path does not exist
createFile(path) undefined Creates a new file; the target must not exist and its parent directory must exist
createDirectory(path) undefined Creates one directory level; the target must not exist and its parent must exist
writeFile(path, text) undefined Overwrites an existing regular file; it does not create the file
writeFile(path, text, override) undefined Overwrites when override is true; refuses to write when it is false
appendFile(path, text) undefined Appends text to an existing regular file, followed by the system line separator
readLine(path) string or null Reads the entire file, despite the method name; logs and returns null on failure
readLines(path) string[] or null Reads all lines without their line terminators; logs and returns null on failure

I/O failures in createFile, createDirectory, writeFile, and appendFile are logged and do not produce a success result. writeFile(path, text) overwrites and truncates the existing file by default.

const directory = "kubejs/server_scripts/kjsutils_demo"
const relativeFile = `${directory}/example.txt`

if (!KJSutilsCommon.existPath(directory)) {
    KJSutilsCommon.createDirectory(directory)
}

if (!KJSutilsCommon.existPath(relativeFile)) {
    KJSutilsCommon.createFile(relativeFile)
}

KJSutilsCommon.writeFile(relativeFile, "First line")
KJSutilsCommon.appendFile(relativeFile, "Second line")

// readLine/readLines
const text = KJSutilsCommon.readLine(relativeFile)
const lines = KJSutilsCommon.readLines(relativeFile)

JSON

Every JSON method accepts two string arguments:

KJSutilsCommon.method(jsonOrPath, key)
  • jsonOrPath may be JSON text or the path to a JSON file within the game directory.
  • Passing a JavaScript object directly is unreliable; use JSON.stringify(object) first.
Method Returns on success Invalid JSON, wrong root, or missing key
getJsonStringValue(jsonOrPath, key) string null
getJsonNumberValue(jsonOrPath, key) number null
getJsonBooleanValue(jsonOrPath, key) boolean false
getJsonDoubleValue(jsonOrPath, key) number 0.0
getJsonObjectValue(jsonOrPath, key) String null
getJsonArrayStringValue(jsonOrPath, key) string[] null
getJsonArrayNumberValue(jsonOrPath, key) number[] null
getJsonArrayDoubleValue(jsonOrPath, key) number[] null
ModifyJsonValue(jsonOrPath, key, value) string null
ModifyJsonValue(jsonOrPath, key, value, format) string null

For the boolean and double getters, false and 0.0 can be either real values or failure fallbacks; check the log when this distinction matters. An incompatible value type can still cause the underlying Gson conversion to throw.

const data = JSON.stringify({
    name: "Alex",
    age: 18,
    enabled: true,
    ratio: 1.25,
    names: ["Alex", "Steve", "Sam"],
    scores: [10, 25, 30],
    weights: [1.5, 2.25],
    json: {
        test: "a",
        as: "b"
    }
})

KJSutilsCommon.getJsonStringValue(data, "name")              // "Alex"
KJSutilsCommon.getJsonNumberValue(data, "age")               // 18
KJSutilsCommon.getJsonBooleanValue(data, "enabled")          // true
KJSutilsCommon.getJsonDoubleValue(data, "ratio")             // 1.25
KJSutilsCommon.getJsonArrayStringValue(data, "names")        // ["Alex", "Steve", "Sam"]
KJSutilsCommon.getJsonArrayNumberValue(data, "scores")       // [10, 25, 30]
KJSutilsCommon.getJsonArrayDoubleValue(data, "weights")      // [1.5, 2.25]
KJSutilsCommon.getJsonObjectValue(data, "json") // {"test":"a","as":"b"}
KJSutilsCommon.ModifyJsonValue(data, "name", "张四")         // {"name":"张四","age":18,"enable":true,"ratio":1.25...}
KJSutilsCommon.ModifyJsonValue(data, "name", "张四", true)   // The only difference from the usage above is whether the returned JSON is formatted or indented, e.g.:

/**
 * {
 *     "name": "张四",
 *     "age":18,
 *     ...
 * }
 */

// A file within the game directory can also be used as the source.
KJSutilsCommon.getJsonStringValue("kubejs/config/example.json", "name")

File Downloads

Download is synchronous and blocking. It has three overloads:

KJSutilsCommon.Download(url, path)
KJSutilsCommon.Download(url, path, tempPath)
KJSutilsCommon.Download(
    url,
    path,
    tempPath,
    timeout,
    downloadTimeout,
    headerName,
    headerValue
)
Argument Type Description
url string Download URL; use trusted HTTPS endpoints
path string Target file path, including the file name
tempPath string Complete temporary file path, not a directory; must differ from path
timeout number Connection timeout in seconds; must be greater than 0
downloadTimeout number Timeout for the entire HTTP request in minutes; must be greater than 0
headerName string Optional header name; only one custom header is supported
headerValue string Optional header value; both name and value must be non-null to add it

The two shorter overloads use a 30-second connection timeout, a 5-minute request timeout, and no custom header. When tempPath is omitted, the temporary file is placed next to the target with .tmp appended to its file name.

The method returns true only when the final HTTP status is exactly 200 and the temporary file is moved successfully. A successful download replaces an existing target. Other status codes, network errors, timeouts, and move failures normally log an error and return false. Parent directories for the target and temporary file are not created automatically.

const downloaded = KJSutilsCommon.Download(
    "https://example.com/data.json",
    "kubejs/downloaded-data.json"
)

const downloadedWithOptions = KJSutilsCommon.Download(
    "https://example.com/data.json",
    "kubejs/downloaded-data.json",
    "kubejs/downloaded-data.json.part",
    15,
    5,
    "User-Agent",
    "KJSutils/2.0.1"
)

Download caveats:

  • The call runs on the current script thread, so a large file or slow connection can block the game.
  • There is no file-size limit, checksum, signature, or content-type validation.
  • Do not download concurrently to the same target or reuse a temporary file.
  • The current implementation does not truncate an existing temporary file. Use a path that does not exist, and remove stale .tmp or custom temporary files left by an abnormal shutdown.
  • Path validation happens before the request. An invalid path or one outside the game directory may throw instead of returning false.

FancyMenu Integration

The following methods are available in client_scripts only when FancyMenu is installed:

Method Returns Behavior
SetFMVariable(name, value) undefined Creates or updates a FancyMenu user variable; value is a string
RemoveFMVariable(name) undefined Removes one user variable
getFMVariable(name) FancyMenu Variable or null Returns the variable object, or null when it does not exist
existFMVariable(name) boolean Tests whether the variable exists
initFMVariable() undefined Reloads and initializes FancyMenu's user-variable storage; normally unnecessary
ClearAllFMVariable() undefined Removes all FancyMenu user variables

FancyMenu persists variable changes to its user-variable file. ClearAllFMVariable() removes every user variable, so use it with care.

// kubejs/client_scripts/example.js
if (typeof KJSutilsClient !== "undefined") {
    KJSutilsClient.SetFMVariable("example", "hello")

    if (KJSutilsClient.existFMVariable("example")) {
        const variable = KJSutilsClient.getFMVariable("example")
    }

    KJSutilsClient.RemoveFMVariable("example")
}

Events

This mod registers two events for KubeJS:

  1. KJSUtilsEvents.playerLeftDimension - Player leaves a dimension

  2. KJSUtilsEvents.playerEnteredDimension - Player enters a dimension

// Example server_scripts

KJSUtilsEvents.playerEnteredDimension(event => {
    let server = event.getServer()

    server.tell(`${event.player.username} entered ${event.to.location()}`)
})

KJSUtilsEvents.playerLeftDimension(event => {
    let server = event.getServer()

    server.tell(`${event.player.username} left ${event.from.location()}`)
})

KJSUtilsEvents.playerEnteredDimension("minecraft:the_nether", event => {
    let server = event.getServer()

    server.tell(`${event.player.username} entered the Nether`)
})

KJSUtilsEvents.playerLeftDimension("minecraft:the_end", event => {
    let server = event.getServer()

    server.tell(`${event.player.username} left the End`)
})

Building from Source

JDK 21 is required. The built JAR is written to build/libs.

.\gradlew.bat build
./gradlew build

Screenshots

Gallery

This project has no gallery images yet.

Versions

Files

Relations

Project Relations

More like this

Similar Mods

Suggestions use data such as tags, dependencies, dependents, descriptions, titles, and more to rank how much they overlap with this mod.

On ModDex

Community snapshot

0
Ratings
0
Followers
0
In stacks

By the numbers

Statistics

<1,000
Downloads
Last Updated
Created
Last synced
When ModDex last fetched this project from CurseForge or Modrinth. Every project is re-checked on a schedule, and any project that ships a new file is synced automatically within hours of the release.
New file updates sync automatically
How syncing works