What should i do to throw Mysql's results another js file

44 Views Asked by At

It's my first JS therefore it may be very novice question. I'd like to pass sql results made by SQLQUERY.js to MAIN.js but i don't know how to handle.

SQLQUERY.js

var mysql = require('mysql')
var db = require('./db/db.js');
var connection = mysql.createConnection(db);
var fs = require('fs')

connection.connect();
const sql = fs.readFileSync('./src/db/sql/selectTimeNotOnWork.sql').toString();
const sql2 = fs.readFileSync('./src/db/sql/selectTimeNotOnWorkCount.sql').toString();

var firstResult
var secondResult
connection.query(sql2,function (error, results, fields) {
if (error) throw error; 
 firstResult = results[0].count;
 return firstResult;
});

connection.query(sql,function (error, results, fields) {
if (error) throw error; 
 secondResult= results[0].name
 return secondResult;
});

exports ={firstResult,secondResult}

MAIN.JS

・・・・
require(./SQLQUERY.js)

controller.hears(['test'], botScope, async(bot, message) => {
    console.log(firstResult)
    console.log(secondResult)
    await bot.reply(message, firstResult);
});
1

There are 1 best solutions below

1
On

When you do a require() you can either require the whole export object or use destructuring.

So in MAIN.JS you would do something like:

{firstResult, secondResult} = require('./SQLQUERY.js')

And then those two values would be available in the MAIN.js code. At least that's how I do it when I need to import specific values from the export, not the entire object. I'm not an expert either so I don't know if a simple require('./SQLQUERY') would make these objects available.