0

I want to make a basic website with a local persistent database. I'm using sql.js but it seems that it's saving the data to webstorage instead of the .db file. Is my code wrong or is sql.js. Is sql.js not the right tool for this job or is my code bad?

This is my code:

async function initializeDatabase() {
  const sqlPromise = initSqlJs({
    locateFile: () => `src/modules/sql-wasm.wasm`
  });
  
  const dataPromise = fetch("src/db/sql2.db").then(res => res.arrayBuffer());
  const [SQL, buf] = await Promise.all([sqlPromise, dataPromise]);
  
  const db = new SQL.Database(new Uint8Array(buf));
  db.run("CREATE TABLE IF NOT EXISTS items (id INTEGER PRIMARY KEY, quantity INTEGER)")  
  db.exec("INSERT INTO items (id, quantity) VALUES (32, 34)")

}
Trax
  • 1,445
  • 5
  • 19
  • 39

1 Answers1

1

HTTP servers don't allow arbitrary writes to URLs, so client-side code can't overwrite the data on any URL it is passed (imagine how long it would take for Google's homepage to be vandalised if that wasn't the case).

If you want to write to a database on the server, then you'll need to use a server-side technology (you could use Node.js if you want to stick to JavaScript) and then either submit a form, use Ajax, or use a WebSocket to pass data to and from the server.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I'm looking for a way to store data on a local network, no server involved. – Trax Aug 25 '23 at 18:21
  • `fetch("src/db/sql2.db")` isn't going to work without a server anyway. You **need** a server, even if it is only accessible on your LAN. – Quentin Aug 25 '23 at 18:25