Reputation: 37
I'm new to javascript and need to know how to create a global function or class that can access by every other page on the website when it is required
mysqlConnection.js
function mysql.connection () {
const mysql = require('mysql');
const con = mysql.createConnection({
host: "hostname",
user: "username",
password: "password",
database: "database",
});
};
script.js
mysql = require('mysqlConnection.js');
mysql.connection();
con.connect(function (err) {
if (err) throw err;
// Query
con.query(sql, function (err, result) {
if (err) throw err;
// Result
});
});
Upvotes: 0
Views: 316
Reputation: 1174
Then you could do it like this:
/* config.js */
const mysql = require('mysql');
const configDB = mysql.createConnection({
multipleStatements: true,
port: 3306,
host: 'XXXXX',
user: 'XXXXX',
password: 'XXXXX',
database: 'XXXXX',
});
module.exports = configDB;
Then you simply import it to each file where you need it:
/* main.js */
const configDB = require('./config.js');
configDB.query(query, (err, data) => {
(....)
Upvotes: 1