Retrieve data from sqlite query Node.js
15,263
Node is asynchronous!!!. lista is returned from the module before the db.all function completes.
You either need to pass a callback into the select function or return a promise. The callback approach would look something like this:
exports.select = function (cb){
var lista = [];
var db = new sqlite3.Database(file);
db.all("SELECT * FROM usuarios", function(err,rows){
if(err) return cb(err);
let contador = 0;
rows.forEach(function (row) {
lista[contador] = row.nombre + ";" + row.cedula + ";" + row.edad + ";"
+ row.pais; });
db.close();
return cb(null, lists);
});
}
Author by
A.rodriguez
Updated on June 14, 2022Comments
-
A.rodriguez about 2 years
I'm currently trying to retrieve data from a sqlite query in node.js, the sql function is on a diferent file so i'm exporting it as a module and then call the function from the index.js. But when i try to retrieve the data the function returns a null value.
Here is my code
Index.js
var express = require("express"); var body_parser = require("body-parser"); var app = express(); var db = require('./dbhandler.js'); app.set("view engine", "jade"); app.get("/data",function(req,res){ let data = db.select(); res.send(data); }); app.get("/",function(req,res){ res.render("index"); }); app.listen(8888);
dbhandler.js
var sqlite3 = require("sqlite3"); const file = "hr"; exports.select = function (){ var lista = []; var db = new sqlite3.Database(file); db.all("SELECT * FROM usuarios", function(err,rows){ let contador = 0; rows.forEach(function (row) { lista[contador] = row.nombre + ";" + row.cedula + ";" + row.edad + ";" + row.pais; }); }); db.close(); return lista; }