i have use the node_sqlite3 module and i have try the following example:
var sqlite = require('sqlite3').verbose();
var db = new sqlite.Database("/var/www/signals/db/app3.db");
var matrixSignals = new Array();
var i;
i = 0;
db.all('SELECT * FROM tbl_signals', function(err,rows){
rows.forEach(function(row) {
matrixSignals[i] = new Object();
matrixSignals[i].signalID = row.signalID;
matrixSignals[i].connID = row.connID;
i++;
});
db.close();
console.log('1:' + matrixSignals.length);
});
console.log('2:' + matrixSignals.length);
in the console output 1 the length is correct but in the console output 2 the length is always 0. How i will set the matrixSignals as a global variable?
The reason this doesn't work has to do with how Node.js operates in general. In node, all code is executed asynchronously; at the time you are logging output 2, matrixSignals still has a length of 0. This is because after you fire off the database query, the code continues to execute. Logging output 1 is only executed after the database query has finished, which is why it returns the correct results.
For this reason, the simple answer to your question is that there is no way to set matrixSignals to be a global variable. If all of your logic is truly dependent on the values in that array, then your logic should be in the callback to the database call - so that it only executes that code once the data has been retrieved from the database. If you just want the syntax to be cleaner, you could potentially use something like node-promise (https://github.com/kriszyp/node-promise) but I think that's probably more effort than its worth.