0

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
  });
});
1

1 Answer 1

1

Use module.exports

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) => {
 (....)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.