Home > Back-end >  getting values from sqlite database and store in an array -Nodejs
getting values from sqlite database and store in an array -Nodejs

Time:06-08

I want to store the information in the SQLite database in arrays. When I write it as below, the output is undefined.

let hostnames = [];
let usernames = [];
let passwords = [];
let commands = [];
let status = [];
let ids = [];
let mac = [];
 
//read from sqlite

var sqlite3=require('sqlite3').verbose();

var db=new sqlite3.Database('../database/database.sqlite',(err)=>{
    if(err){
        return console.error(err.message);
    }
    console.log('Connected...');
});

db.all('SELECT * FROM Users ORDER BY id',[],(err,rows)=>{
    if(err){
        return console.error(err.message);
    }
    rows.forEach((row)=>{
        
       hostnames.push(row.name);
       usernames.push(row.username);
       passwords.push(row.password);
       commands.push(row.command);
       status.push(row.status);
       mac.push(row.mac);
       ids.push(row.id);
       
    
       
    });
});

console.log("hostnames",hostnames);

When I want to reach hostnames from outside the forEach; console.log("hostnames",hostnames); the console output is undefined.I'm not sure how I should do it. I would be glad if you help

CodePudding user response:

It's not working because this is asynchronous code. It must have callback such that it responds after the database query finishes.

documentation: https://nodejs.org/en/knowledge/getting-started/control-flow/what-are-callbacks/

example

In this example I’m passing a callback to the function DataExt and calling it after it finishes.

let hostnames = [];

var sqlite3=require('sqlite3').verbose();


function DataExt(db, callback) {
    db.all('SELECT * FROM Users ORDER BY id',[],(err,rows)=>{
        if(err){
            return console.error(err.message);
        }
        else
        {           
            rows.forEach((row)=>{
                hostnames.push(row.name);
             });
            
            return callback(false, hostnames);
              
        }

    });
}

var db=new sqlite3.Database('../database/database.sqlite',(err)=>{
    if(err){
        return console.error(err.message);
    }
    console.log('Connected...');
});

DataExt(dtb, function(err, content) {
    if(err) throw(err);
    ExtractedHostnames = content;
    console.log("hostnames", ExtractedHostnames);
})
  • Related