Dewan159
Dewan159

Reputation: 3074

Using sql.js in an Electron application

I am new to Electron. It's pure awesome, and getting started is super fun and easy. For some time now I have been trying to find a "database" solution to use in my application. Of course there is the Web SQL/local storage options, but I am trying to use SQLite. I found sql.js, which is great and easy to use. I could get everything to run correctly put I cannot save/update the database file! Here is the code:

    var remote = require('remote'),
    fileSystem = remote.require('fs'),
    sql = remote.require('./nodeModules/sql.js'),
    database = new sql.Database(fileSystem.readFileSync('./database.sqlite'));

    database.run('CREATE TABLE IF NOT EXISTS products (ID integer primary key autoincrement, name text, price integer, stock integer)');

    // Save the data back to the file
    var data = database.export();
    var buffer = new Buffer(data);
    fileSystem.writeFileSync("./database.sqlite", buffer);

But I am getting this error from "Buffer": Uncaught TypeError: must start with number, buffer, array or string. Have you run across this issue before ?

Upvotes: 5

Views: 3942

Answers (2)

patrickmoffitt
patrickmoffitt

Reputation: 1

I believe you have to read and write the database to the folder returned by calling:

electron.app.getPath('userData')
I created an example project showing how to use sql.js in Electron.

Upvotes: 0

codewise
codewise

Reputation: 626

I was unable to reproduce this issue on node v6.2.2 (npm v3.9.4) on Windows 10 and OS X 10.11.5. The code is nearly identical to yours:

fs.writeFileSync("filename.sqlite", new Buffer(db.export()));

Check out this repo for more information: https://github.com/codewisdom/electron-sqljs

Upvotes: 1

Related Questions