Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

162
Visualizações
Export an array containing mysql results to another javascript file

I making use of node.js + mysql in my app. I would like to export an array containing results/rows of an SQL select statement to another javascript file and display the values stored in the array.

stats.js

var phonenum='0718900000'
var sql='SELECT name,surname,age from Tbluser WHERE number=?;'
conn.query(sql,[phonenum],function(err,results){
                      if (err){
                        throw err;
                      };
                      /*if (results==0)
                      {
                        let dealersMessage="❌ User not found"
                      }*/
                      
              console.log(results)      
             var datastatagentStore=[];
             results.forEach(item =>{
                 module.exports=datastatagentStore.push({
                        name:item.name,
                        surname:item.surname,
                        age:item.age,
                      })
                    }) 

app.js

 var{datastatagentStore}=require('../functions/stats.js')

 console.log('User details '+datastatagentStore);
about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

Based on a comment above:

My goal is to execute the query and display the results to the user every time the user selects the 'view my details' button.

Then you don't want to export the results, you want to export the function which performs the query. That function would return [a Promise which resolves to] the results.

If conn.query returns a Promise then it might look something like this:

var getUserDetails = function (phonenum) {
  var sql='SELECT name,surname,age from Tbluser WHERE number=?;'
  return conn.query(sql, [phonenum], function(err, results) {
    if (err) {
      throw err;
    };
    console.log(results)      
    var datastatagentStore = [];
    results.forEach(item => {
      datastatagentStore.push({
        name:item.name,
        surname:item.surname,
        age:item.age,
      })
    });
    return datastatagentStore;
  });
};

module.exports = getUserDetails;

Though I don't know if conn.query does return a Promise. If it doesn't, you can manually create one:

var getUserDetails = function (phonenum) {
  return new Promise(function (resolve, reject) {
    var sql='SELECT name,surname,age from Tbluser WHERE number=?;'
    conn.query(sql, [phonenum], function(err, results) {
      if (err) {
        reject(err);
      };
      console.log(results)      
      var datastatagentStore = [];
      results.forEach(item => {
        datastatagentStore.push({
          name:item.name,
          surname:item.surname,
          age:item.age,
        })
      });
      resolve(datastatagentStore);
    });
  });
};

module.exports = getUserDetails;

Note the use of resolve and reject here to manually complete the Promise. But however you structure it, the overall point is that your module export wouldn't be the results of having executed the query, it would be the function to execute the query. And since executing the query is an asynchronous operation, that function should return a Promise.

Then you can use it like any other asynchronous operation:

var datastatagentStore = require('../functions/stats.js');

datastatagentStore('0718900000').then(function (details) {
  console.log('User details ', details);
});
about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda