Please note that I am a total noob when it comes to Node.js.
I have created a WebSockets app that will send server status and usage every second when a client connects (through basic authentications so that only the authorized clients can contact).
I want to add disk usage info to the data and is using the nodejs-disks module for that. And this is the function I've created to get the info I need:
function getDiskStats()
{
var output = {
count: 0,
space: {
total: 0,
used: 0,
free: 0
}
};
df.drives(function(err, drives)
{
df.drivesDetail(drives, function(err, data)
{
output.count = data.length;
for(var i = 0; i < data.length; i++)
{
output.space.total += parseInt(data[i].total);
output.space.used += parseInt(data[i].used);
output.space.free += parseInt(data[i].available)
}
});
});
return output;
}
But when the output is returned, everything is 0 and if I log variable in the console right after the for
loop I get the values. My guess is that its because of the async method nodejs-disks
uses to get the data. I am not sure what I should do next and I HAVE google a lot but couldn't find a good solution.
Thanks!
Like @mevernom said, you are returning your object before any of the asynchronous objects have a chance to work.
You can modify your function to work asynchronously by making your getDiskStats
function take a callback that it calls when everything else is done.
function getDiskStats(callback) {
var output = {
count: 0,
space: {
total: 0,
used: 0,
free: 0
}
};
df.drives(function(err, drives) {
if (err) return callback(err); // stop on error
df.drivesDetail(drives, function(err, data) {
if (err) return callback(err); // stop on error
output.count = data.length;
for(var i = 0; i < data.length; i++) {
output.space.total += parseInt(data[i].total);
output.space.used += parseInt(data[i].used);
output.space.free += parseInt(data[i].available)
}
// done processing, call callback
callback(null, output);
});
});
}
You would then have to use your function like
getDiskStats(function(err, value) {
// do stuff!
});
Because your getDistStats
returned immediately, before callbacks finished their tasks.
If you are not comfortable with asynchronous nature, perhaps you could try async module.