2

package.json

{
  "main": "app/app.js",
  "scripts": {
    "postinstall": "install-app-deps",
    "start": "electron ."
  },
  "dependencies": {
    "sqlite3": "^3.1.8"
  },
  "devDependencies": {
    "electron-prebuilt-compile": "^1.7.9",
    "electron-builder": "^19.37.2",
    "electron-rebuild": "^1.6.0"
  }
}

index.html

<body>
  <div id="app"></div>
  <div id='database'></div>
  <script>
    var sqlite3 = require('sqlite3').verbose();
    var db = new sqlite3.Database('./test.db')
    db.serialize(function () {
      var stmt = db.all("select * from BK_GROUP", function (_, rows) {
        console.log('end1');
      })
      var stmt2 = db.all("select * from BK_GROUP", function (_, rows) {
        console.log('end2');
      })
    })
    console.log('out1');
    db.close();
  </script>
  <script src="main.js"></script>
</body>

I expect(according to sqlite3's api document https://github.com/mapbox/node-sqlite3/wiki/Control-Flow) this code should output like this

end1
end2
out1

but real output is

out1
end1
end2 

I follow some instruction on web, install electron-rebuild, and run it

./node_modules/.bin/electron-rebuild

also it found sqlite3 and rebuild it, but this doesn't help.

I aslo add postinstall in package.json's scripts.

But if I run this code in pure node.js env, it outputs correct result.


More, if I run this code in electron, it outputs correctly(first print end, then out). The only difference is this code open database in memory, above open a file database locate on hard driver.

<body>
    <h1>electron-boilerplate-sqlite</h1>
    <ul id="database">
    </ul>
    <script>
      var sqlite3 = require('sqlite3').verbose();
      var db = new sqlite3.Database(':memory:');

      db.serialize(function() {
        db.run("CREATE TABLE lorem (info TEXT)");

        var stmt = db.prepare("INSERT INTO lorem VALUES (?)");
        for (var i = 0; i < 10000; i++) {
          stmt.run("Ipsum " + i);
        }

        stmt.finalize();

        var rows = document.getElementById("database");
        db.each("SELECT rowid AS id, info FROM lorem", function(err, row) {
          var item = document.createElement("li");
          item.textContent = "" + row.id + ": " + row.info;
          rows.appendChild(item);
        });
        console.log('end')
        setTimeout(() => console.log('delay'), 1000);

      });
      console.log('out')

      db.close();
    </script>
  </body>

What can I do now?

1 Answer 1

0

you misunderstood javascript, db serialize is callback function so the order of console.log is correct, but keep in mind one

Since serialize() doesn't return until the last of its internal queries has completed, using it will hold off the close() until the query has completed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.