G
G
godand2020-01-22 22:08:53
MySQL
godand, 2020-01-22 22:08:53

How to correctly send requests to other files?

Good evening everyone. For a long time I have been struggling with one booger that appears when trying to make a request in another js file. I'll show you with an example.
database.js

var mysql = require("mysql");

module.exports = {
    Pool : null,
    Connect : function(callback) {
        this.Pool = mysql.createConnection({
            host: 'localhost',
            user: 'root',
            password: 'admin',
            database: 'server'
        })
        this.Pool.connect(function(err) {
            if(err) {
                console.log('[Database ERROR] ' + err.message);
                throw err;
            } else {
                console.log(`\x1b[92m[DATABASE]\x1b[0m Соединение установлено.`);
            }
        })
    }
}

main.js
require('./module.js');

const DB = require('./database.js');

DB.Connect(() => {
      DB.Pool.query("CREATE TABLE IF NOT EXISTS `mdb_players` (`ID` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, `Name` varchar(24) NOT NULL, `Money` int(11) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8;", (err) => {
    if (err) console.log('\x1b[91m[Database]\x1b[0m ' + err.message);
  });
});

Now begins the next stage, which I can not delve into. For example, we have a module.js file. It is in this file that I need to make a request without reconnecting to the database, that is, do not use DB.Connect(), but immediately use DB.query().
module.js
const DB = require('./database.js')

DB.Pool.query("CREATE TABLE IF NOT EXISTS `mdb_players` (`UID` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, `Name` varchar(24) NOT NULL, `Money` int(11) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8;", (err) => {
    if (err) console.log('\x1b[91m[Database]\x1b[0m ' + err.message);
  });

It would be possible to use DB.Connect() in other files, but then the console will repeatedly display a message with an established connection.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question