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;
}
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;
}
Share
Improve this question
asked Jun 12, 2016 at 15:52
A.rodriguezA.rodriguez
2701 gold badge4 silver badges11 bronze badges
1 Answer
Reset to default 11Node is asynchronous!!!. lista is returned from the module before the db.all function pletes.
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);
});
}