Squighopper25 Squighopper25 - 17 days ago 5
Node.js Question

Cannot store value inside .get method from npm library 'Sqlite3'

Problem: I cannot get a variable into the correct scope, using the .get function from the nodejs library 'sqlite3'.

Explanation: Even though I have declared the variable 'image_path' in a scope from which it can be returned out of the function, when I assign it a value within the .get method, the scope of image_path appears to change; It is no longer able to be returned from the function 'returnImagePath' as expected.

Aim: I simply want to create a function with which I can query an Sqlite3 database using nodejs and return a value. If there is a better way of doing that then what I am currently trying, I will accept it as an answer.

Example:

var sqlite3 = require('sqlite3');

var dataBaseFile = 'test.db';
var dataBase = new sqlite3.Database(dataBaseFile);

function returnImagePath(id){
var image_path;
dataBase.serialize(function(){
var statementReturnImagePath = dataBase.prepare(`SELECT image_path FROM images WHERE id = ${id}`);
statementReturnImagePath.run();
statementReturnImagePath.finalize();
dataBase.get(`SELECT image_path FROM images WHERE id = 1`, function(error, row){
image_path = row.image_path;
console.log(image_path); //image_path is defined here, and logs as expected
});
dataBase.close();
});
console.log(image_path); //image_path is undefined here
return image_path;
}
var asdf = returnImagePath(1);
console.log(asdf); //this, therefore doesn't work

Answer

In the node.js world, you have to understand what is asynchronous function. If a process requires IO operations, you cannot just return the data from that process, instead you have to "wait" for the data. We usually achieve this with a callback function.

Here is the example for you,

var sqlite3 = require('sqlite3');

var dataBaseFile = 'test.db';
var dataBase = new sqlite3.Database(dataBaseFile);

//callback is a function which accept (err, data)
function returnImagePath(id, callback){
    dataBase.serialize(function(){
        dataBase.get('SELECT image_path FROM images WHERE id = ' + id, function(error, row){
            if (error) {
                //stop and return error if error occurs
                return callback(error, null);
            }
            image_path = row.image_path; 
            console.log(image_path); //image_path is defined here, and logs as expected
            //now you get the image path and return it with callback
            callback(null, image_path);
            dataBase.close();
        });
    });
}
returnImagePath(1, function(err, image_path) {
    if (err) { //capture error(s)
        return console.error(err);
    }
    console.log(image_path); //now you get the image path
});