lil-gui

Save Server

This example only works on localhost.

When using lil-gui to fine tune parameters, it can be tedious to copy and paste values back and forth between the GUI and your source. This example uses a local node server to write the contents of gui.save() to a JSON file on disk.

The server has a single endpoint /save which expects a JSON value in the request body.

./save-server.js
/* eslint-env node */
const fs = require( 'fs' );
const http = require( 'http' );

// Port the save server runs on.
const PORT = 4000;

// Path to the JSON file where values are written.
const VALUES = './values.json';

// The address and port of your local webserver.
const ALLOWED = 'http://localhost:3000';

const server = http.createServer( function( req, res ) {

	if ( req.url === '/save' ) {

		let data = '';

		req.on( 'data', chunk => data += chunk );
		req.on( 'end', () => {

			fs.writeFile( VALUES, data, err => {

				res.setHeader( 'Access-Control-Allow-Origin', ALLOWED );

				// Send error status 500 if the write failed.
				res.writeHead( err ? 500 : 200 );
				res.end();

				console.log( '/save', err || 'success' );

			} );

		} );

	}

} );

server.listen( PORT );

Run the server with the following. You don't need to install any dependencies.

node save-server.js

The client code uses fetch, both to load values from the JSON file, and to POST values to our save-server "API".

This page:
import GUI from '../../dist/lil-gui.esm.js';

const PORT = 4000;

async function save() {
	return await fetch( `http://localhost:${PORT}/save`, {
		method: 'POST',
		body: JSON.stringify( gui.save() )
	} );
}

async function load() {
	try {
		const response = await fetch( `./values.json` )
		const values = await response.json();
		gui.load( values );
	} catch ( e ) {
		// File might be empty, or not exist yet.
		console.error( 'Load failed', e );
	}
}

const params = {
	number: 0,
	string: "yo",
	color: 0xaa00ff,
	save
};

const gui = new GUI();

gui.add( params, 'number' );
gui.add( params, 'string' );
gui.addColor( params, 'color' );

gui.add( params, 'save' );

load();

If your environment supports loading JSON modules, you can skip fetch for loading.

import values from './values.json';

// build gui ...

gui.load( values );