Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving Uint8array to a sqlite file

I am using sql.js as an admin interface for a SQLITE3 database.

Basically sql.js provides an export method that returns a Uint8Array for the developer to further handle.

Goal: Have the user press a button and a "Save As" dialogue pops up to save a file that is a valid sqlite3 database.

What I've tried: This save code block I've found in various parts of the web researching this issue.

        /* Uint8Array */
        var binArray = db.export();

        var saveData = (function () {
            var a = document.createElement("a");
            document.body.appendChild(a);
            a.style = "display: none";
            return function (data, fileName) {

                /* Is JSON.stringify necessary? */
                var json = JSON.stringify(data),

                    /* Is type: "octet/stream" correct? */
                    blob = new Blob([json], {type: "octet/stream"}),
                    url = window.URL.createObjectURL(blob);
                a.href = url;
                a.download = fileName;
                a.click();
                window.URL.revokeObjectURL(url);
            };
        }());

        saveData(binArray, "sqldb.sql");

It properly saves a file called "sqldb.sql", but I get "Invalid file format" error from a database client software.

like image 647
Blenderer Avatar asked Feb 01 '26 13:02

Blenderer


1 Answers

  1. The type should be the MIME application/octet-stream when you have binary data and no other MIME is more befitting
  2. Calling JSON.stringify makes no sense, you end up with a String that looks like '{"0":254, "1":128, ...}' when you already have the binary data as you want to save it

Combining these two points, the function returned should look more like this

    // ...
        return function (data, fileName) {
            var blob = new Blob([data], {type: "application/octet-stream"}),
                url = window.URL.createObjectURL(blob);
            a.href = url;
            a.download = fileName;
            a.click();
            window.URL.revokeObjectURL(url);
        };

You may also need to consider if the Uint8Array is really a complete .sql file in it's own right, i.e. if you did the call to get it not in a browser/ajax, but so it was written directly to disc (e.g. with curl or direct linked) would that file be a valid sql file?

like image 56
Paul S. Avatar answered Feb 04 '26 01:02

Paul S.