Export connection method - create db.js file
    const mysql = require('mysql')

class DB {

connection;
constructor(){

this.connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'training_db'
})
}

connect(){
this.connection.connect();
return this.connection;
}

}
exports.DB = DB;
Import db.js and test the code
    const {DB} = require("./db.js");

const conn = new DB().connect();

conn.query('SELECT 1 + 1 AS solution', function (err, rows, fields) {
if (err) throw err

console.log('The solution is: ', rows[0].solution)
})

conn.end()
Test
    node test_db.js