Save characters and the world
Keep each player's level, perks, SPECIAL, inventory and position across sessions with getCharacter and setCharacter, and carry the world's date, clock and weather across a restart.
A server that forgets everyone on restart is a deathmatch server. You will give players their character back when they rejoin, exactly where they left it, and bring the world’s calendar and clock back after a restart, so a server that ran for a month still says it has.
This is the persistence feature of the default gamemode, rebuilt step by step. It stores one JSON
file per player, which is enough for a small community. The shape carries over unchanged to a real
database.
What you will learn
Section titled “What you will learn”- What a
CharacterDocumentholds, and what it leaves out. - When a character can be read and written:
playerCharacterLoad. - Using Node’s own modules from a resource.
- Writing a file so that a crash cannot corrupt it.
- Restoring
World’s clock and calendar, and the order that matters.
persistence/ package.json tsconfig.json src/server/ index.ts imports store.ts read and write JSON safely characters.ts players world.ts the clock and the calendar1. What a character is
Section titled “1. What a character is”player.getCharacter() returns the whole progression of a character as one plain object, ready for
JSON.stringify:
| Field | What it holds |
|---|---|
experience, level, perkPoints |
Progression |
values |
Actor value bases: SPECIAL, and any a script set |
perks |
Perk ranks held |
current |
Health, ActionPoints and Rads as they stood |
inventory |
What they carry |
nickname, version |
Who it was taken from, and the document’s format |
It does not include where the player is. Save player.position, player.heading and
player.getSpace() beside it.
setCharacter(document) takes it back, and brings the player’s game to it. Anything the document
leaves out stays as it is, so you can also use it to set just a level, or just the inventory.
Both only work once the character is established, which is what playerCharacterLoad announces.
Before that, getCharacter returns null and setCharacter returns false.
2. Files, safely
Section titled “2. Files, safely”Server scripts run on Node, so its built-in modules are there. The scripting declarations do not
include Node’s, so declare the few calls you use. That keeps the resource compiling against
@falloutmp/types alone:
interface FileSystem { existsSync(path: string): boolean; readFileSync(path: string, encoding: "utf8"): string; writeFileSync(path: string, data: string): void; renameSync(from: string, to: string): void; mkdirSync(path: string, options: { recursive: boolean }): void;}declare const require: (module: "node:fs") => FileSystem;declare const process: { cwd(): string };
const fs: FileSystem = require("node:fs");
/** Beside the server binary, not inside the resource: a reload must not touch it. */export const kDataDir = `${process.cwd()}/fmp-data`;
export function writeJson(path: string, value: unknown): void { const folder = path.slice(0, path.lastIndexOf("/")); fs.mkdirSync(folder, { recursive: true }); // Write beside, then move over. A crash halfway leaves the last good file in place. fs.writeFileSync(`${path}.tmp`, JSON.stringify(value, null, 2)); fs.renameSync(`${path}.tmp`, path);}
export function readJson<T>(path: string): T | null { if (!fs.existsSync(path)) return null; return JSON.parse(fs.readFileSync(path, "utf8")) as T;}The write-then-rename is the part to keep even if you change everything else. writeFileSync
straight onto the real file truncates it first; a server killed in the middle leaves a player with a
half-written, unparseable save and no way back. A rename within one folder either happens or
does not.
If you would rather install @types/node, add "node" to types in your tsconfig.json and drop
the declarations.
3. Save and restore a player
Section titled “3. Save and restore a player”Nobody logs in on a server without accounts, so the nickname is the key. Strip anything a file name cannot hold:
import { kDataDir, readJson, writeJson } from "./store.js";
interface SavedPlayer { version: number; savedAt: string; character: CharacterDocument; position: { x: number; y: number; z: number }; heading: number; space: PlayerSpace | null;}
const kVersion = 1;const kAutosaveMs = 5 * 60 * 1000;
const pathOf = (player: Player): string => `${kDataDir}/characters/${player.nickname.replace(/[^A-Za-z0-9_-]/g, "_")}.json`;
export function save(player: Player, why: string): void { const character = player.getCharacter(); if (character === null) return; // not established yet: nothing of theirs to keep
const { x, y, z } = player.position; const saved: SavedPlayer = { version: kVersion, savedAt: new Date().toISOString(), character, position: { x, y, z }, heading: player.heading, space: player.getSpace(), }; try { writeJson(pathOf(player), saved); console.log(`${player.nickname} saved (${why}), level ${character.level}`); } catch (error) { console.error(`${player.nickname} not saved: ${String(error)}`); }}
function load(player: Player): SavedPlayer | null { try { const saved = readJson<SavedPlayer>(pathOf(player)); return saved !== null && saved.version === kVersion ? saved : null; } catch (error) { console.error(`${player.nickname}: save unreadable: ${String(error)}`); return null; }}
/** Interior if they were in one, otherwise their worldspace, the Commonwealth if unknown. */function spaceFor(space: PlayerSpace | null): { worldSpace: number } | { interiorCell: number } { if (space !== null && space.interiorCell !== 0) return { interiorCell: space.interiorCell }; return { worldSpace: space?.worldSpace || 0x3c };}
Events.on("playerCharacterLoad", (player: Player) => { const saved = load(player); if (saved === null) { console.log(`${player.nickname} is new here`); return; } player.setCharacter(saved.character); const { x, y, z } = saved.position; player.teleport(new Vector3(x, y, z), saved.heading, spaceFor(saved.space));});
Events.on("playerDisconnect", (player: Player) => save(player, "left"));
// A crash or a power cut costs at most this much progress.setInterval(() => { for (const player of Player.all()) save(player, "autosave");}, kAutosaveMs);A few things worth knowing:
- Restore in
playerCharacterLoad, notplayerReady. The character is established when the player’s game first reports it, which is a separate message from the one that makes them ready. Until it arrives,setCharacterreturnsfalse. - Do not race your spawn. If another handler teleports joining players to a spawn point on
playerReady, the two teleports arrive close together and either may land last. Have the spawn skip players who have a save (check for the file there too), so a returning player is only moved once. versionis for you. When you changeSavedPlayer, bump it and either migrate old files inloador treat them as new characters. Never guess at an old shape.- Copy the position.
player.positionis a liveVector3; destructure it into a plain object before saving, as above.
4. The world’s clock
Section titled “4. The world’s clock”World holds one clock, calendar and weather for everyone. None of it survives a restart on its own:
the server starts at its defaults. Save it on the same occasions, and restore it once, when the
resource starts:
import { kDataDir, readJson, writeJson } from "./store.js";
interface SavedWorld { version: number; date: WorldDate; daysPassed: number; hour: number; timeScale: number; lightningEnabled: boolean; weather: number;}
const kPath = `${kDataDir}/world.json`;
export function saveWorld(): void { const saved: SavedWorld = { version: 1, date: World.date, daysPassed: World.daysPassed, hour: World.hour, timeScale: World.timeScale, lightningEnabled: World.lightningEnabled, weather: World.weather, }; try { writeJson(kPath, saved); } catch (error) { console.error(`world not saved: ${String(error)}`); }}
function restoreWorld(): void { let saved: SavedWorld | null; try { saved = readJson<SavedWorld>(kPath); } catch (error) { console.error(`world save unreadable: ${String(error)}`); return; } if (saved === null || saved.version !== 1) return;
World.setDaysPassed(saved.daysPassed); World.setDate(saved.date.year, saved.date.month, saved.date.day); World.setHour(saved.hour); World.setTimeScale(saved.timeScale); World.setLightningEnabled(saved.lightningEnabled); World.setWeather(saved.weather, true);}
restoreWorld();Events.on("worldDayChange", () => saveWorld());Events.on("playerDisconnect", () => saveWorld());setInterval(saveWorld, 5 * 60 * 1000);Each setter touches only its own part of the clock: setDaysPassed leaves the date alone, setDate
leaves the hour alone, and setHour leaves both alone. Restoring all three is therefore three calls,
in any order. Day count and date are separate on purpose: the day count is what the game’s own timers
measure in (vendor restocks, crops), and the date is what the Pip-Boy shows.
World.setWeather(..., true) swaps the saved weather in at once rather than fading into it, so a
restart does not open with a storm clearing.
5. Put it together
Section titled “5. Put it together”import "./characters.js";import "./world.js";Try it
Section titled “Try it”-
Build and load:
Server console refreshensure persistence -
Join, walk somewhere memorable, pick up some items. With the default gamemode,
/xp 2000. -
Disconnect. The console logs
<you> saved (left), level ..., andfmp-data/characters/<you>.jsonappears next to the server binary. -
Rejoin. You are back where you stood, at the same level, with the same inventory.
-
/time 22and restart the server. It is still night.
What to change next
Section titled “What to change next”- A database. Replace
readJsonandwriteJsonwith calls to SQLite or Postgres from npm. Keep the document shape and the version check. - More of the world. The shop stock from Shopkeeper and trades and the open
bounty from Bounty hunt are both plain data that fit in
world.json. - Death penalties. On
playerDeath, take a share ofcharacter.experiencebefore the next save.