Cannot assign values to variable exports
asynchronously, which is what you’re trying to do. You need the value you want to export to be obtained synchronously.
As most of the operations done in a db are done by asynchronous functions, there is no way to export anything that results from these operations through the exports
of the js.
What you can do is export a function that accepts a callback as an argument and execute its query within that function. For example:
//Conexao com BD MySQL
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'username',
password: '123456',
database: 'database'
});
connection.connect(function (err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
exports.query = function (cb) {
connection.query('SELECT * from informacoes;', function (err, rows, fields) {
if (!err) {
var resultado = rows;
cb(null, resultado);
} else {
console.log('Erro ao realizar a consulta');
cb(err);
}
});
}
Another way would be to use an IIFE (Immediately Invoked Function Expression) along with async, but this will only work with ES7 onwards. Another detail is that the mysql driver you are using does not work with Promises, so you would have to create a function that encapsulates the query and returns a file. That way your code would look like this:
function queryWithPromise (query) {
return new Promise((resolve, reject) => {
connection.query(query, function (err, rows, fields) {
if (err) return reject(err)
resolve(rows)
})
}
}
module.exports = (async function () {
const resultado = await queryWithPromise('SELECT * from informacoes;')
return resultado
})()
Then you use await when importing the file:
let informacoes
(async function () {
informacoes = await require('./caminho/pro/arquivo.js')
})()
what mistake? you did not put in your question
– Vitor Ceolin
I edited the question... When I check the file I should export, it is empty
– Bruno Henrique