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.
const fs = require( 'fs' );
const http = require( 'http' );
const PORT = 4000;
const VALUES = './values.json';
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 );
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.
The client code uses fetch, both to load values from the JSON file, and to POST values to our save-server "API".
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 ) {
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';
gui.load( values );