Files
@amxts/core/fs reads and writes files the way Node's fs does:
import * as fs from "@amxts/core/fs";
const rulesFile = `${server.configsDir}/myplugin/rules.txt`;
server.addCommand("/rules", ({ player }) => showRules(player));
function showRules(player: Player) {
const text = fs.readFileSync(rulesFile);
if (text == null) return; // no such file
for (const line of text.split("\n")) console.log(line);
fs.appendFileSync(`${server.dataDir}/myplugin-rules.log`, `${player.name} read the rules\n`);
}
Every function has a synchronous form and a promise form, for await:
| Synchronous | Promise | Does |
|---|---|---|
readFileSync(path) → string | null | readFile(path) → Promise<string> | reads the whole file as text |
readBytesSync(path) → Uint8Array | null since v0.3 | readBytes(path) → Promise<Uint8Array> | reads the whole file as bytes |
writeFileSync(path, data) → boolean | writeFile(path, data) → Promise<void> | writes text or bytes since v0.3 to the file, replacing what was there |
appendFileSync(path, data) → boolean | appendFile(path, data) → Promise<void> | adds text or bytes to the end, making the file if needed |
existsSync(path, options?) → boolean | exists(path, options?) → Promise<boolean> | a file or a folder is there; { game: true } since v0.3.1 looks in every folder the game reads from |
readdirSync(path) → string[] | null | readdir(path) → Promise<string[]> | the names in a folder, without . and .. |
mkdirSync(path, options?) → boolean | mkdir(path, options?) → Promise<void> | makes a folder; { recursive: true } makes the missing folders above it too |
unlinkSync(path) → boolean since v0.3 | unlink(path) → Promise<void> | deletes a file |
renameSync(from, to) → boolean since v0.3 | rename(from, to) → Promise<void> | moves or renames a file |
rmdirSync(path) → boolean since v0.3 | rmdir(path) → Promise<void> | deletes an empty folder |
statSync(path) → Stats | null since v0.3 | stat(path) → Promise<Stats> | size, mtime, isFile(), isDirectory() |
extractSync(archive) → ArchiveEntry[] since v0.3 | extract(archive) → Promise<ArchiveEntry[]> since v0.3.1 | the files of an archive |
import * as fs from "@amxts/core/fs";
async function saveMap() {
await fs.mkdir(`${server.dataDir}/myplugin`, { recursive: true });
await fs.writeFile(`${server.dataDir}/myplugin/last-map.txt`, server.map);
}
fs.readFile("missing.txt").catch((error) => console.log(error.message));
// ENOENT: no such file or directory, open 'missing.txt'
Paths
A path is relative to the game folder, cstrike/, as for any AMX Mod X
plugin. server.configsDir is the configs folder (addons/amxmodx/configs)
and server.dataDir the data folder (addons/amxmodx/data), wherever the
server keeps them. Keep your plugin's files in a folder or under a name of
its own: configs/myplugin/, data/myplugin-stats.txt.
Text
Files are read and written as UTF-8 text. A file is read whole, whatever its size. A byte-order mark at the start of a file is kept, as in Node.
Bytes and archives since v0.3
A file that is not text - a map, a sound, an archive - is bytes: a
Uint8Array. readBytesSync reads one, and writeFileSync and
appendFileSync take a Uint8Array or an ArrayBuffer as well as text.
fs.extract(bytes) gives the files of an archive, each an ArchiveEntry
with its path inside the archive and its data. It tells the archive's
kind by its first bytes; it reads zip archives:
import * as fs from "@amxts/core/fs";
async function downloadMap(name: string) {
const response = await fetch(`https://maps.example.com/${name}.zip`);
for (const entry of await fs.extract(await response.arrayBuffer())) {
const folder = entry.path.substring(0, entry.path.lastIndexOf("/"));
if (folder.length > 0) await fs.mkdir(folder, { recursive: true });
await fs.writeFile(entry.path, entry.data);
}
}
A large download can go straight into a file - request of @amxts/core/kit
with its file
option - and fs.readBytes reads it back for extract.
Bytes are read and written only inside the game folder: a path that is absolute or has
.. in it gives null or false. extract rejects with an
Error for an archive with such a path, for a kind it does not read - a
rar or a 7z archive, its message naming the kinds it reads - and for an
archive that is encrypted or damaged. Of a zip archive it reads the files
stored as they are or deflated - what zip tools write - and lists no folders.Without holding the server since v0.3.1
The server runs a frame at a time, and a frame waits for the plugin's code.
extract, readBytes, and writeFile and appendFile given bytes do
their work on the server's worker thread and settle on a later frame, so
unpacking a map of megabytes does not hold the game. Their synchronous
forms, extractSync, readBytesSync and writeFileSync, do it at once,
inside the frame: fine for a small file, a lag for the players with a large
one.
Bytes written with writeFile and appendFile land in the order of the
calls. Text goes through the same file functions as writeFileSync, at
once.
Compression since v0.3.1
@amxts/core/zlib compresses and inflates bytes the way Node's zlib does,
in three formats:
| Synchronous | Promise | Format |
|---|---|---|
gzipSync(data), gunzipSync(data) | gzip(data), gunzip(data) | gzip, a .gz file |
deflateSync(data), inflateSync(data) | deflate(data), inflate(data) | zlib: deflate with zlib's header and checksum |
deflateRawSync(data), inflateRawSync(data) | deflateRaw(data), inflateRaw(data) | raw deflate, as a zip archive holds a file |
Each takes a Uint8Array or an ArrayBuffer - the compressing ones text
too, as UTF-8 - and gives a Uint8Array. The promise forms work on the
server's worker thread, as extract does:
import * as fs from "@amxts/core/fs";
import * as zlib from "@amxts/core/zlib";
async function saveRun(name: string, recording: Uint8Array) {
await fs.writeFile(`${server.dataDir}/myplugin/${name}.rec.gz`, await zlib.gzip(recording));
}
async function loadRun(name: string): Promise<Uint8Array> {
return zlib.gunzip(await fs.readBytes(`${server.dataDir}/myplugin/${name}.rec.gz`));
}
Data that is not whole data of its format, cut short or of another format, throws an
Error in a synchronous call and rejects a promise, with zlib's
words: incorrect header check, unexpected end of file. Inflating stops
at 64 MB: past it the call fails rather than the server running out of
memory.JSON
JSON reads and writes JSON text as in JavaScript. JSON.parse is told
what it reads - JSON.parse<Stats>(text), or a type the value goes to - and
builds that object, its arrays, Records and fields included:
import * as fs from "@amxts/core/fs";
interface Stats {
kills: number;
deaths: number;
lastMap?: string;
}
const statsFile = `${server.dataDir}/myplugin/stats.json`;
function loadStats(): Stats {
const text = fs.readFileSync(statsFile);
if (text == null) return { kills: 0, deaths: 0 };
return JSON.parse(text);
}
function saveStats(stats: Stats) {
fs.writeFileSync(statsFile, JSON.stringify(stats, null, 2));
}
Text that is not JSON is a SyntaxError; a value of another kind than the
type says - text where a number goes, a field that must be there and is not -
is a TypeError that names the field. Catch them with try/catch.
JSON.stringify leaves out a field that is undefined, writes a Date as
its ISO text and an object with a toJSON() as what that gives.
A Uint8Array since v0.3.1 is base64 text in JSON both ways:
JSON.stringify writes its bytes so - not JavaScript's object of indexes -
and JSON.parse reads base64 text into a field typed Uint8Array.
For settings a server owner edits, a typed config of config-core reads YAML, JSON and INI alike.
When it fails
A synchronous function says it failed by its result: null from
readFileSync and readdirSync, false from writeFileSync,
appendFileSync and mkdirSync - a folder that does not exist, say. A
promise function rejects with an Error whose message starts with ENOENT,
as Node's do (mkdir's with EEXIST or ENOENT).
The work is done at once either way: a promise function has settled by the time it returns.
The operating system
import { EOL, platform } from "@amxts/core/os";
if (platform() == "linux") console.log("running on Linux");
const lines = ["first", "second"].join(EOL); // "\r\n" on Windows, "\n" on Linux
platform() is "win32" or "linux", and EOL the line ending of that
system.
In a test, the fake server keeps the game folder in memory:
server.writeFile(path, text) before the plugin reads, server.file(path)
after it writes (Testing).