I am trying to create global const variables and I am wondering if this is the good way?
const sqlite3 = require('sqlite3')
Object.defineProperty(global, "db", {
value: new sqlite3.Database(__dirname + '/database.db')
})
I am trying to create global const variables and I am wondering if this is the good way?
const sqlite3 = require('sqlite3')
Object.defineProperty(global, "db", {
value: new sqlite3.Database(__dirname + '/database.db')
})
"Do NOT use global variables! If you start running your application with multiple processes you will get screwed very badly."
In order to use a globally accessible variable, you sould use a module.
eg:
In a file named db.js
const sqlite3 = require('sqlite3');
exports.current = new sqlite3.Database(__dirname + '/database.db');
To use it:
const db = require('./db.js'); // instanciated only once
db.current.all("SELECT * FROM playlists", [], (err, rows) => {
if (err) {
throw err;
}
rows.forEach((row) => {
console.log(row.name);
});
});
...
Refer to another answer of the same How to use global variable in node.js?