1

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')
})
July333
  • 251
  • 1
  • 6
  • 15
  • Possible duplicate of [Can global constants be declared in JavaScript?](https://stackoverflow.com/questions/4174552/can-global-constants-be-declared-in-javascript) – laggingreflex May 19 '18 at 15:34

1 Answers1

0

"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?

Air One
  • 316
  • 2
  • 6