[英]Retrieve data from sqlite query Node.js
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. 我目前正在尝试从node.js中的sqlite查询中检索数据,sql函数位于其他文件上,因此我将其导出为模块,然后从index.js调用该函数。 But when i try to retrieve the data the function returns a null value.
但是,当我尝试检索数据时,该函数返回空值。
Here is my code 这是我的代码
Index.js 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 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;
}
Node is asynchronous!!!. 节点是异步的! lista is returned from the module before the db.all function completes.
在db.all函数完成之前,从模块返回lista。
You either need to pass a callback into the select function or return a promise. 您要么需要将回调传递给select函数,要么返回一个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);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.