31
exports.allProbes = function() {
    var rows = db.all("SELECT * FROM probes;");
    return rows;
};

main:
var json_values = allProbes();

Is it possible to do something like that? I mean, without using a callback function: just, read data (sync mode) from the db. and return a json formatted output?

Thanks.

3
  • What module are you using? It all depends on if it has synchronous support. Commented Mar 22, 2013 at 17:24
  • i've installed sqlite3 with the following command: "npm install sqlite3" Commented Mar 22, 2013 at 17:29
  • I need the same as you OP. I need guarantee that my queries are executed in order. Wrapping it in promises is a PITAS Commented Aug 30, 2020 at 15:10

4 Answers 4

43

There are a few npm packages such as better-sqlite3 and sqlite-sync that allow for synchronous SQLite queries. Here's an example:

var sqlite = require("better-sqlite3");
var db = new sqlite("example.db");

var rows = db.prepare("SELECT * FROM probes").all();
console.log(rows);
Sign up to request clarification or add additional context in comments.

Comments

23

You will not be able to do that with sqlite3. With sqlite3 module the only available mode of operation is asynchronous execution, and you will have to use a callback. Eg.

exports.allProbes = function(callback) {
    db.all("SELECT * FROM probes;", function(err, all) {
        callback(err, all);  
    });
};

Then in your code:

var json_values;

allProbes(function(err, all) {
    json_values = all;
});

Check sqlite3 API Docs.

2 Comments

or just.. db.all("SELECT * FROM probes;", callback),
Can't we use a promise?
0

you can make an asynchronous function using async/await

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
-3

You have to install sql.js with npm install --save sql.js

Rest follow the below steps :

var fs = require('fs');    
var sql = require('sql.js');    
var bfr = fs.readFileSync('/tmp/db.sqlite');

var db = new sql.Database(bfr);
db.each('SELECT * FROM test', function (row) {

  console.log(row);

});

More details you can get on the below this link : https://discuss.atom.io/t/how-to-access-a-local-db-on-windows-through-electron/22400/13

1 Comment

This doesn't answer the question. The file is read synchronously, but the database query still requires an async callback.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.