Reputation: 399
I have a db.js file that has this line in the top to connect to the database.. i call this file to run queries from inside other js files:
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('./mydatabase');
db.serialize(function() {
db.each("SELECT rowid AS id, info FROM lorem", function(err, row) {
console.log(row.id + ": " + row.info);
});
db.close();
If i require() this above file 4 times in different files, does this mean sqlite database will be initialized that many times?
I want to initalize it only the first time..
Is this inefficient? Is there a more efficient way?
Upvotes: 5
Views: 2320
Reputation: 3214
Official documentation: https://github.com/mapbox/node-sqlite3/wiki/Caching
Sqlite3 module can do caching internally if you use require('sqlite3').cached
, i.e. it won't create new connections on new sqlite3.cached.Database(file)
as long as string held by file
is identical, but reuse existing ones. See in the source for yourself here:
https://github.com/mapbox/node-sqlite3/blob/master/lib/sqlite3.js
However, you should not depend on that. Do some kind of dependency injection, it will save many headaches along the way. In simplest form it will be writing your modules that they export functions accepting database object as their argument:
//module1.js
module.exports = function(db){
db.serialize(...)
//dostuff
}
//start.js
var sqlite3 = require('sqlite3').verbose();
var module1 = require('./module1.js');
var db = new sqlite3.Database('./mydatabase');
module1(db);
Upvotes: 3