logo

hxFileManager

Cross-platform file management library for Haxe. Provides a clean async API backed by a native thread pool — file I/O, JSON helpers, file watching, hashing, batch operations, and HTTP — all with a consistent interface across Windows, Linux, and Mac.

v1.4.0 MIT Windows Linux Mac cpp

Installation

Install via haxelib, then call FileManager.init() before any async operation.

haxelib install hxFileManager
import hxFileManager.FileManager;
import hxFileManager.HttpManager;

FileManager.init(); // start the thread pool (call once at startup)

FileManager

hxFileManager.FileManager

Async file operations powered by a configurable worker thread pool. All *Async methods are non-blocking and deliver results via callbacks.

Variables 2
static final rootDir : String
SYNC

The directory containing the running executable. Empty string on unsupported targets.

trace(FileManager.rootDir); // e.g. "D:/myproject/bin"
static var isAdmin : Bool
SYNC

Whether the process is running with administrator / root privileges. Evaluated once at startup.

if (FileManager.isAdmin) trace("Running as admin");
Thread Pool 3
static init(numThreads : Int = 4) : Void
SYNC

Start the worker thread pool. Must be called before any async method. Safe to call multiple times — subsequent calls are no-ops.

ParameterTypeDescription
numThreadsIntNumber of worker threads to spawn. Default 4. optional
FileManager.init();    // 4 threads (default)
FileManager.init(8);  // 8 threads
static dispose() : Void
SYNC

Drain the task queue and terminate all worker threads. Call when the application is shutting down.

FileManager.dispose();
static inline enqueueAsync(fn : Void->Void) : Void
ASYNC

Push arbitrary work onto the shared thread pool. Throws in debug builds if init() has not been called.

FileManager.enqueueAsync(() -> trace("on worker thread"));
Existence Checks 4
static inline fileExists(filePath : String) : Bool
SYNC

Returns true if the path exists and is a file.

if (FileManager.fileExists("save.dat")) trace("save found");
static inline folderExists(folderPath : String) : Bool
SYNC

Returns true if the path exists and is a directory.

if (FileManager.folderExists("assets")) trace("assets dir exists");
static fileExistsAsync(filePath : String, onResult : Bool->Void) : Void
ASYNC

Async version of fileExists.

FileManager.fileExistsAsync("save.dat", exists -> trace(exists));
static folderExistsAsync(folderPath : String, onResult : Bool->Void) : Void
ASYNC

Async version of folderExists.

FileManager.folderExistsAsync("assets", exists -> trace(exists));
Read / Write 11
static readFileAsync(filePath : String, onSuccess : String->Void, ?onError : String->Void) : Void
ASYNC

Read a text file asynchronously.

FileManager.readFileAsync("config.txt", content -> trace(content));
static readFileBytesAsync(filePath : String, onSuccess : Bytes->Void, ?onError : String->Void) : Void
ASYNC

Read a file as raw Bytes asynchronously.

FileManager.readFileBytesAsync("image.png", bytes -> trace(bytes.length));
static writeFileAsync(filePath : String, content : String, ?onSuccess : Float->Void, ?onError : String->Void) : Void
ASYNC

Write a text file asynchronously. Parent directories are created automatically. onSuccess receives elapsed seconds.

FileManager.writeFileAsync("log.txt", "hello", t -> trace("wrote in " + t + "s"));
static writeBytesAsync(filePath : String, bytes : Bytes, ?onSuccess : Float->Void, ?onError : String->Void) : Void
ASYNC

Write raw bytes to a file asynchronously.

FileManager.writeBytesAsync("data.bin", myBytes);
static appendFileAsync(filePath : String, content : String, ?onDone : Void->Void, ?onError : String->Void) : Void
ASYNC

Append text to a file. Creates the file if it does not exist.

FileManager.appendFileAsync("log.txt", "\nnew line");
static prependFileAsync(filePath : String, content : String, ?onDone : Void->Void, ?onError : String->Void) : Void
ASYNC NEW

Prepend text to a file by reading existing content and rewriting with new content at the front.

FileManager.prependFileAsync("log.txt", "=== START ===\n");
static truncateFileAsync(filePath : String, ?onDone : Void->Void, ?onError : String->Void) : Void
ASYNC NEW

Erase all content from a file without deleting it.

FileManager.truncateFileAsync("cache.txt");
static safeWriteAsync(filePath : String, content : String, ?onDone : Void->Void, ?onError : String->Void) : Void
ASYNC NEW

Atomically write a file. Backs up existing content to .bak first and restores on failure. Removes the backup on success.

FileManager.safeWriteAsync("config.json", newJson);
static readLinesAsync(filePath : String, onSuccess : Array<String>->Void, ?onError : String->Void) : Void
ASYNC NEW

Read a file and split it into an array of lines.

FileManager.readLinesAsync("data.csv", lines -> trace(lines.length + " rows"));
static writeLinesAsync(filePath : String, lines : Array<String>, ?onDone : Void->Void, ?onError : String->Void) : Void
ASYNC NEW

Write an array of strings to a file joined by newlines.

FileManager.writeLinesAsync("list.txt", ["alpha", "beta", "gamma"]);
static readFileBase64Async(filePath : String, onSuccess : String->Void, ?onError : String->Void) : Void
ASYNC NEW

Read a file and return its contents Base64-encoded.

FileManager.readFileBase64Async("icon.png", b64 -> sendToServer(b64));
JSON 3
static readJsonAsync(filePath : String, onResult : Dynamic->Void, ?onError : String->Void) : Void
ASYNC

Read and parse a JSON file asynchronously.

FileManager.readJsonAsync("config.json", cfg -> trace(cfg.version));
static writeJsonAsync(filePath : String, data : Dynamic, ?onDone : Float->Void, ?onError : String->Void, pretty : Bool = false) : Void
ASYNC

Serialise data to JSON and write to a file. Pass pretty: true for indented output.

FileManager.writeJsonAsync("config.json", {version: 2}, null, null, true);
static patchJsonAsync(filePath : String, patchFn : Dynamic->Dynamic, ?onDone : Void->Void, ?onError : String->Void) : Void
ASYNC NEW

Read a JSON file, pass the parsed object through a transform function, then write the result back.

FileManager.patchJsonAsync("scores.json", data -> {
    data.highScore = 9999;
    return data;
});
Metadata 4
static getFileMetadataAsync(filePath : String, onResult : StringMap<Dynamic>->Void, ?onError : String->Void) : Void
ASYNC NEW

Returns a map with keys "size" (Int) and "lastModified" (Date).

FileManager.getFileMetadataAsync("save.dat", meta -> trace(meta.get("size")));
static getFileSizeAsync(filePath : String, onResult : Int->Void, ?onError : String->Void) : Void
ASYNC NEW

Get file size in bytes.

FileManager.getFileSizeAsync("video.mp4", size -> trace(size + " bytes"));
static getFolderSizeAsync(folderPath : String, onResult : Int->Void, ?onError : String->Void) : Void
ASYNC NEW

Get total size of all files inside a folder recursively.

FileManager.getFolderSizeAsync("assets", total -> trace(total + " bytes"));
static getLastModifiedAsync(filePath : String, onResult : Date->Void, ?onError : String->Void) : Void
ASYNC NEW

Get the last modification date of a file.

FileManager.getLastModifiedAsync("save.dat", date -> trace(date.toString()));
Path Helpers 4
static inline getFileExtension(filePath : String) : String
SYNC

Returns the lowercase extension without the leading dot, e.g. "txt", "json".

FileManager.getFileExtension("DATA.JSON"); // "json"
static inline getFileName(filePath : String) : String
SYNC

Returns the file name including extension.

FileManager.getFileName("assets/sprites/hero.png"); // "hero.png"
static inline getFileNameWithoutExt(filePath : String) : String
SYNC

Returns the file name without its extension.

FileManager.getFileNameWithoutExt("assets/sprites/hero.png"); // "hero"
static inline getParentDir(filePath : String) : String
SYNC

Returns the parent directory of a path.

FileManager.getParentDir("assets/sprites/hero.png"); // "assets/sprites"
Copy / Move / Delete 7
static copyFileAsync(sourcePath : String, destPath : String, ?onDone : Void->Void, ?onError : String->Void) : Void
ASYNC NEW

Copy a single file. Parent directories are created if needed.

FileManager.copyFileAsync("src.txt", "backup/src.txt");
static copyFolderAsync(source : String, dest : String, ?onDone : Void->Void, ?onError : String->Void) : Void
ASYNC

Recursively copy a folder and all its contents.

FileManager.copyFolderAsync("assets", "backup/assets");
static moveFileAsync(oldPath : String, newPath : String, ?onDone : Void->Void, ?onError : String->Void) : Void
ASYNC NEW

Move a file to a new path.

FileManager.moveFileAsync("temp.dat", "saves/slot1.dat");
static moveFolderAsync(sourcePath : String, destPath : String, ?onDone : Void->Void, ?onError : String->Void) : Void
ASYNC NEW

Move a folder to a new path.

FileManager.moveFolderAsync("old_saves", "saves/archive");
static deletePathAsync(path : String, ?onDone : Void->Void, ?onError : String->Void) : Void
ASYNC

Delete a file or recursively delete a directory tree.

FileManager.deletePathAsync("temp");
static duplicateFileAsync(filePath : String, ?suffix : String = "_copy", ?onDone : String->Void, ?onError : String->Void) : Void
ASYNC NEW

Copy a file next to itself with a suffix before the extension. onDone receives the new path.

FileManager.duplicateFileAsync("save.dat", "_backup", newPath -> trace(newPath));
// produces: "save_backup.dat"
static writeFileBase64Async(filePath : String, base64 : String, ?onDone : Void->Void, ?onError : String->Void) : Void
ASYNC NEW

Decode a Base64 string and write the resulting bytes to a file.

FileManager.writeFileBase64Async("icon.png", receivedBase64);
Folder Operations 6
static createFolderAsync(folderPath : String, ?onSuccess : Void->Void, ?onError : String->Void) : Void
ASYNC

Create a directory and any missing parents recursively.

FileManager.createFolderAsync("saves/slot1/items");
static listFilesAsync(folderPath : String, onResult : Array<String>->Void, ?onError : String->Void) : Void
ASYNC

List the immediate contents of a folder.

FileManager.listFilesAsync("assets", entries -> trace(entries));
static listFilesDeepAsync(folderPath : String, onResult : Array<String>->Void, ?onError : String->Void) : Void
ASYNC NEW

Recursively list all file paths under a folder.

FileManager.listFilesDeepAsync("assets", all -> trace(all.length + " files"));
static listFoldersAsync(folderPath : String, onResult : Array<String>->Void, ?onError : String->Void) : Void
ASYNC NEW

List only subdirectory names inside a folder.

FileManager.listFoldersAsync("saves", dirs -> trace(dirs));
static countFilesAsync(folderPath : String, onResult : Int->Void, recursive : Bool = false, ?onError : String->Void) : Void
ASYNC NEW

Count files in a folder. Set recursive: true to include subdirectories.

FileManager.countFilesAsync("assets", n -> trace(n), true);
static cleanEmptyFoldersAsync(folderPath : String, ?onDone : Int->Void, ?onError : String->Void) : Void
ASYNC NEW

Remove all empty subdirectories recursively. onDone receives the count of removed directories.

FileManager.cleanEmptyFoldersAsync("output", n -> trace(n + " dirs cleaned"));
Watchers 3
static watchFolder(path : String, onChange : Void->Void, intervalMs : Int = 1000) : Int
ASYNC NEW

Poll a folder for changes using mtime-hash comparison. Returns a watch ID used to cancel via stopWatcher.

var id = FileManager.watchFolder("assets", () -> trace("changed!"));
FileManager.stopWatcher(id);
static watchFile(filePath : String, onChange : Void->Void, intervalMs : Int = 500) : Int
ASYNC NEW

Poll a single file for modifications using mtime comparison. Returns a watch ID.

var id = FileManager.watchFile("config.json", () -> reloadConfig());
static stopWatcher(watchId : Int) : Void
SYNC

Stop a running file or folder watcher by its ID.

FileManager.stopWatcher(watchId);
Hashing & Comparison 3
static hashFileMd5Async(filePath : String, onResult : String->Void, ?onError : String->Void) : Void
ASYNC NEW

Compute the MD5 hash of a file. Returns a 32-character hex string.

FileManager.hashFileMd5Async("installer.exe", hash -> trace(hash));
static hashFileSha256Async(filePath : String, onResult : String->Void, ?onError : String->Void) : Void
ASYNC NEW

Compute the SHA-256 hash of a file. Returns a 64-character hex string.

FileManager.hashFileSha256Async("installer.exe", hash -> trace(hash));
static compareFilesAsync(pathA : String, pathB : String, onResult : Bool->Void, ?onError : String->Void) : Void
ASYNC NEW

Compare two files byte-for-byte. Callback receives true if identical.

FileManager.compareFilesAsync("v1.dat", "v2.dat", eq -> trace(eq ? "same" : "different"));
Batch Operations 5
static batchWriteAsync(entries : Map<String,String>, ?onDone : Void->Void, ?onError : String->Void) : Void
ASYNC NEW

Write multiple files in a single async operation.

FileManager.batchWriteAsync(["a.txt" => "hello", "b.txt" => "world"]);
static batchReadAsync(paths : Array<String>, onResult : Map<String,String>->Void, ?onError : String->Void) : Void
ASYNC NEW

Read multiple files in a single async operation. Returns a map of path → content.

FileManager.batchReadAsync(["a.txt", "b.txt"], map -> trace(map.get("a.txt")));
static batchDeleteAsync(paths : Array<String>, ?onDone : Void->Void, ?onError : String->Void) : Void
ASYNC NEW

Delete multiple paths in a single async operation.

FileManager.batchDeleteAsync(["tmp1.txt", "tmp2.txt", "tmp3.txt"]);
static batchCopyAsync(pairs : Array<{src:String, dst:String}>, ?onDone : Void->Void, ?onError : String->Void) : Void
ASYNC NEW

Copy multiple source/destination file pairs in one operation.

FileManager.batchCopyAsync([{src: "a.txt", dst: "backup/a.txt"}]);
static batchMoveAsync(pairs : Array<{src:String, dst:String}>, ?onDone : Void->Void, ?onError : String->Void) : Void
ASYNC NEW

Move multiple source/destination file pairs in one operation.

FileManager.batchMoveAsync([{src: "inbox/a.txt", dst: "archive/a.txt"}]);
Utilities 7
static downloadFileAsync(url : String, savePath : String, ?headers : Map<String,String>, ?onProgress : (Int,Int)->Void, ?onDone : Void->Void, ?onError : String->Void, retries : Int = 3) : Void
ASYNC NEW

Download a URL to a local path with automatic retry. onProgress receives (bytesReceived, total).

FileManager.downloadFileAsync(
    "https://example.com/file.zip", "downloads/file.zip",
    null, (r, t) -> trace('$r/$t'), () -> trace("done!")
);
static generateUniqueFileNameAsync(basePath : String, onResult : String->Void) : Void
ASYNC NEW

Return a unique path by appending an incrementing counter if the file already exists, e.g. file (2).txt.

FileManager.generateUniqueFileNameAsync("report.pdf", path -> saveAs(path));
static createTempFileAsync(onResult : String->Void, prefix : String = "tmp_", suffix : String = "") : Void
ASYNC NEW

Create an empty temporary file in the system temp directory and return its path.

FileManager.createTempFileAsync(path -> trace(path), "myapp_", ".tmp");
static createTempFolderAsync(onResult : String->Void, prefix : String = "tmp_") : Void
ASYNC NEW

Create a temporary directory in the system temp directory and return its path.

FileManager.createTempFolderAsync(path -> trace(path));
static requestAdmin(?onSuccess : Void->Void, ?onError : String->Void) : Void
ASYNC

Request administrator privileges by re-launching the process with elevation. Native cpp targets only.

if (!FileManager.isAdmin) FileManager.requestAdmin(() -> trace("elevated!"));
static getPlatformName() : String
SYNC

Returns "Windows", "Mac", "Linux", or "unknown".

trace(FileManager.getPlatformName()); // "Windows"
static getAppDataPath(appName : String) : String
SYNC

Returns the OS-appropriate app data directory for appName, creating it if needed. Uses %APPDATA% on Windows, ~/Library/Application Support on Mac, and ~/.local/share on Linux.

var path = FileManager.getAppDataPath("MyGame");
// Windows → C:/Users/User/AppData/Roaming/MyGame
Deprecated
These methods are kept for backwards compatibility. They are hidden from IDE autocompletion (@:noCompletion) and will be removed in a future version. Use the async equivalents instead.
DeprecatedUse instead
createFilewriteFileAsync
readFilereadFileAsync
readJsonreadJsonAsync
writeJsonwriteJsonAsync
deletePathdeletePathAsync
safeWritesafeWriteAsync
copyFolderRecursivecopyFolderAsync
getFileSizegetFileSizeAsync
getFolderSizegetFolderSizeAsync
listFileslistFilesAsync
copyFilecopyFileAsync
moveFolder / renameFoldermoveFolderAsync
renameFilemoveFileAsync
deleteFile / deleteFolderdeletePathAsync
createFoldercreateFolderAsync
generateUniqueFileNamegenerateUniqueFileNameAsync
getFileMetadatagetFileMetadataAsync
stopWatchingFolderstopWatcher

HttpManager

hxFileManager.HttpManager

HTTP client with redirect following, retry logic, and JSON helpers. Methods are synchronous — wrap in FileManager.enqueueAsync for non-blocking use.

Variables 3
static var hasInternet : Bool
SYNC

Cached result of the last checkInternet() call. Updated automatically at startup.

if (HttpManager.hasInternet) trace("online");
static var defaultUserAgent : String
SYNC

User-Agent header sent with every request. Default: "hxFileManager".

HttpManager.defaultUserAgent = "MyApp/1.0";
static var defaultTimeout : Int
SYNC

Request timeout in seconds. Default: 10.

HttpManager.defaultTimeout = 30;
GET Requests 6
static requestText(url : String, ?headers : Map<String,String>, maxRedirects : Int = 5, ?onProgress : (Int,Int)->Void) : String
SYNC

Fetch a URL and return the response body as a string. Follows redirects automatically.

var html = HttpManager.requestText("https://example.com");
static requestBytes(url : String, ?headers : Map<String,String>, maxRedirects : Int = 5, ?onProgress : (Int,Int)->Void) : Bytes
SYNC

Fetch a URL and return the raw response bytes. Follows redirects automatically.

var bytes = HttpManager.requestBytes("https://example.com/file.zip");
static getJson(url : String, ?headers : Map<String,String>, onSuccess : Dynamic->Void, ?onError : String->Void) : Void
SYNC NEW

Fetch a URL and parse the response body as JSON.

HttpManager.getJson("https://api.example.com/user/1", user -> trace(user.name));
static getStatusCode(url : String, ?headers : Map<String,String>) : Int
SYNC NEW

Return the HTTP status code for a URL without downloading the body.

var code = HttpManager.getStatusCode("https://example.com"); // 200
static getResponseHeaders(url : String, ?headers : Map<String,String>) : Map<String,String>
SYNC NEW

Return all response headers for a URL as a map.

var h = HttpManager.getResponseHeaders("https://example.com");
trace(h.get("content-type"));
static hasBytes(url : String, ?headers : Map<String,String>) : Bool
SYNC NEW

Returns true if the URL responds with any bytes. Never throws.

if (HttpManager.hasBytes("https://cdn.example.com/asset.png")) downloadIt();
POST / PUT / PATCH / DELETE 5
static postJson(url : String, data : Dynamic, ?headers : Map<String,String>, ?onSuccess : String->Void, ?onError : String->Void) : Void
SYNC

POST a JSON body. Sets Content-Type: application/json automatically.

HttpManager.postJson("https://api.example.com/scores", {player: "Hero", score: 9999});
static postForm(url : String, fields : Map<String,String>, ?headers : Map<String,String>, ?onSuccess : String->Void, ?onError : String->Void) : Void
SYNC NEW

POST URL-encoded form fields.

HttpManager.postForm("https://example.com/login", ["user" => "hero", "pass" => "1234"]);
static putJson(url : String, data : Dynamic, ?headers : Map<String,String>, ?onSuccess : String->Void, ?onError : String->Void) : Void
SYNC NEW

Send a PUT request with a JSON body. Uses X-HTTP-Method-Override: PUT.

HttpManager.putJson("https://api.example.com/user/1", {name: "Hero"});
static patchJson(url : String, data : Dynamic, ?headers : Map<String,String>, ?onSuccess : String->Void, ?onError : String->Void) : Void
SYNC NEW

Send a PATCH request with a JSON body. Uses X-HTTP-Method-Override: PATCH.

HttpManager.patchJson("https://api.example.com/user/1", {score: 100});
static delete(url : String, ?headers : Map<String,String>, ?onSuccess : String->Void, ?onError : String->Void) : Void
SYNC NEW

Send a DELETE request. Uses X-HTTP-Method-Override: DELETE.

HttpManager.delete("https://api.example.com/user/1");
Utilities 4
static downloadTo(url : String, savePath : String, ?headers : Map<String,String>, ?onProgress : (Int,Int)->Void, ?onDone : Void->Void, ?onError : String->Void) : Void
SYNC NEW

Download a URL directly to a local file path.

HttpManager.downloadTo("https://example.com/img.png", "img.png");
static requestWithRetry(url : String, maxAttempts : Int = 3, delayMs : Int = 500, ?headers : Map<String,String>) : Bytes
SYNC NEW

Retry a GET request up to maxAttempts times with delayMs between attempts. Throws after all fail.

var bytes = HttpManager.requestWithRetry("https://example.com/file.zip", 5, 1000);
static checkInternet() : Bool
SYNC

Check connectivity by hitting https://example.com. Updates and returns hasInternet.

if (!HttpManager.checkInternet()) trace("no connection");
static checkInternetAsync(onResult : Bool->Void) : Void
ASYNC NEW

Check internet connectivity asynchronously.

HttpManager.checkInternetAsync(online -> trace(online ? "online" : "offline"));
HttpError
class HttpError

Thrown by requestText, requestBytes, and related methods on failure.

FieldTypeDescription
messageStringError description.
urlStringThe URL that caused the error.
statusIntHTTP status code, or -1 if unavailable.
redirectedBoolWhether the error occurred during a redirect.
try {
    var text = HttpManager.requestText("https://bad.url");
} catch (e:HttpError) {
    trace(e.toString());
    // [HttpManager | ERROR] | Status: 404 | URL: ... | Message: ...
}