Skip to content

Instantly share code, notes, and snippets.

Created July 22, 2022 18:53
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
save/load feature for colyseus schema objects

I'm adding a save/load feature to my WIP game and thought someone might find this small module useful

example usage:

const saveGameData = new SaveGame(); // make a custom schema for saved games data
... /* add all state objects from your game manager to saveGameData */
const serialized = await schemaToString(saveGameData);
... /* save to file, read from file etc. */
const loadedGameData: SaveGame = await stringToSchema(SaveGame, serialized );
... /* take game state object from loadedGameData into your game manager */

import { gzip, unzip } from 'node:zlib';
import { Schema } from '@colyseus/schema';
import { promisify } from 'node:util';
const do_gzip = promisify(gzip);
const do_unzip = promisify(unzip);
export async function schemaToString(fragment: Schema) {
const zipped = await do_gzip(Buffer.from(fragment.encodeAll()));
return zipped.toString('base64');
type Constructor<T extends Schema> = new (...args: unknown[]) => T;
export async function stringToSchema<T extends Schema>(ctor: Constructor<T>, serialized: string) {
const unzipped = await do_unzip(Buffer.from(serialized, 'base64'));
const result = new ctor();
return result;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment