I do a select statement on sqlite3 in node.js. I'd like to have the result in the variable "data" which is defined outside the sqlite code block but it stays empty. Within the sqlite code block the data variable has the correct value. Does anybody know what I'm doing wrong?
Thank you.
/* Client connects via socket.io */
io.on('connection', function(client) {
console.log('Client connected');
/* Client needs data... */
client.on('needData', function(fields) {
var data = [];
var sql_stmt = "SELECT ...";
if(fs.existsSync(db_file)) {
try {
var db = new sqlite3.Database(db_file);
db.all(sql_stmt, function(err, all) {
data = all;
console.log(data); //--> data has valid values
});
db.close();
console.log(data); //--> data is empty
}
catch(e) {
console.log("Error with database. Error: ", e);
}
}
else {
console.log("Database file not found.");
}
client.emit('data', data);
});
});
It happening just because of asynchronous
nature of Node.js
you can handle it with by promises
I recommend to use waterfall method of async module
var async=require('async');
/* Client connects via socket.io */
io.on('connection', function(client) {
console.log('Client connected');
/* Client needs data... */
client.on('needData', function(fields) {
async.waterfall([function(next) {
var sql_stmt = "SELECT ...";
if (fs.existsSync(db_file)) {
try {
var db = new sqlite3.Database(db_file);
db.all(sql_stmt, function(err, all) {
next(null,all)
});
db.close();
} catch (e) {
console.log("Error with database. Error: ", e);
next();
}
} else {
console.log("Database file not found.");
next();
}
}], function(err, data) {
if (!err) {
client.emit('data', data);
}
})
});
});