I've been reading a lot about callbacks, but still don't get it...
I'm executing an async function which adds to an array a string with info about the available disk space.
All this code is in a script, and I'd like to be able to use that array in others. So far I tried to return it and pass it as parameter... but it executes before finishing the task.
var diskspace = require('diskspace');
var fs = require('fs');
var aux;
function getDiskSpace(json){
diskspace.check('C',function(err, total, free, status){
aux=new Object();
aux.name="diskspace";
aux.value=(((total-free)/(1024^3)).toFixed(2)+"MB used, "+(free*100/total).toFixed(2)+"% free");
json.push(aux);
});
aux= new Object();
aux.name="date";
aux.value=(new Date().toLocaleString());
json.push(aux);
aux= new Object();
aux.name="arduinos";
aux.value=JSON.parse(fs.readFileSync("./data/dirs.json","utf8"));
json.push(aux);
}
module.exports=getDiskSpace;
Once in the main program, I send it like JSON:
var array=new Array();
var getDiskSpace=require('./getIndexInfo.js');
getDiskSpace(array);
res.writeHead(200,{"Content-Type": "application/json"});
res.end(JSON.stringify(array));
Can you tell me the proper way to do this? I know this have been discussed a lot, but I've been reading even about promises also, and the more I read the more confused I am, sorry.