Use SQL connection file in NodeJS in other file



  • Hello I tried using SQL connection files with other files but for some reason it always gives me error or doesn't show anything. Can somebody please help me where I am going wrong or is it allowed in BAS?

    Here's the code:
    config

    module.exports = async function () {
        const mysql = require('mysql2');
    
        // create the connection to database
        const connection = mysql.createConnection({
            host: 'localhost',
            user: 'user',
            database: 'user'
        });
    }
    

    Current:

    await require("../mysqlconfig")();
    
    module.exports = async function () {
        await (new Promise((resolve, reject) => {
            connection.query(
                'SELECT * FROM `table` WHERE 1 LIMIT 1',
                function (err, results, fields) {
                    if (err) {
                        reject(err)
                        return
                    }
                    if(results.length>0){
                        console.log(results)
                        console.log(err)
                    }
                    else
                        console.log("Not found")
                        console.log(err)
                    resolve()
                }
            );
        }))
    }
    


  • @Fox @tet-vivi @UserTrue or anyone?



  • Nobody who knows this? Or is it not possible? @support



  • Not sure about node, you should check online about exact code that works.
    But you could maybe use BAS connection to remote database instead.



  • @GaG I can implement it without any problems if I don't use file but because I have to connect to the database everytime I use node it becomes redundant, I just want to make a code where I can connect from 1 file and use that file to connect wherever I want.



  • Still not sure what could be the reason, but maybe you should take a closer look at positioning "resolve()" in your code. Looks like its executed only in else condition in your code. Maybe you should firstly "resolve()" results and after that set "if" condition or go with "try" and "catch" approach.



  • @hippyzipp9 Man, just return your connection object from file import. And use it after in main file. Something like this:

    const connection = await require("../mysqlconfig")();
    

    Just learn a bit more info about node.js usage.



  • @Oyasumi-Punpun Bruhh it worked, thank you so much <3
    Still learning about node :)



  • @GaG No it wasn't the issue, else is not in parenthesis so it's gonna execute anyway. I know that's not the ideal code :P

    P.S- the above guy's solution worked.


Log in to reply