-1

how do i export and use values ​​returned from the date of this function ?

exports.dadosXml = function(){
  
  fs.readFile("./auth/socket_config.json" , "utf8", function(err, data){
    if(data){

      jsonData = JSON.parse(data);
      return  console.log(jsonData);
      
    }else if(err){
      
      return console.log("Erro");
      
    }
    
  });

}
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Marcos Casagrande Dec 09 '19 at 17:16

2 Answers2

0

You can use callback.

exports.dadosXml = function(callback){

  fs.readFile("./auth/socket_config.json" , "utf8", function(err, data){
    if(data){
      jsonData = JSON.parse(data);
      return  console.log(jsonData);

    }else if(err){
      return console.log("Erro");
    }
  });
}

dadosXml(function(data){
    console.log(data);
});

You can use readFileSync but when this action works it blocks others.

exports.dadosXml = function(){
  return fs.readFileSync("./auth/socket_config.json" , "utf8");
}
hurricane
  • 6,521
  • 2
  • 34
  • 44
0

You can change the signature of dadosXml so that it would take a callback function as an argument:

exports.dadosXml = function(callback) {
  fs.readFile('./auth/socket_config.json', 'utf8', function(err, data) {
    if (data) {
      jsonData = JSON.parse(data);
      callback(null, jsonData)
    } else if (err) {
      callback(err)
    }
  });
};

Then, in the module that invokes dadosXml you need to pass a callback function that will work with the data:

dadosXml(function(err, data) {
  if (err) {
    return console.log(err);
  } else {
    console.log('Data was read successfully', data);
  }
});
antonku
  • 7,377
  • 2
  • 15
  • 21