Reputation: 27
This is a function which parses all the usb drives from /dev
folder of a Raspberry Pi. I want to return sda
, ada1
, sdb
, sdb1
as an array, but failed to do so. It does not print out anything when I do console.log(readDeviceList())
. What's wrong with my code?
var usbDeviceList = new Array();
function readDeviceList() {
var usbDeviceList = new Array();
fs.readdir(deviceDir, function (error, file) {
if (error) {
console.log("Failed to read /dev Directory");
return false;
} else {
var usbDevCounter = 0;
console.log("Find below usb devices:");
file.forEach(function (file, index) {
if (file.indexOf(usbDevicePrefix) > -1) {
usbDeviceList[usbDevCounter++] = file;
}
});
console.log(usbDeviceList); // This prints out the array
};
});
console.log(usbDeviceList); // This does not print out the array
return usbDeviceList; // Is this return value valid or not?
}
Upvotes: 0
Views: 60
Reputation: 43073
fs.readdir
is an async
function that takes a callback.
You can either propagate that callback:
function readDeviceList(callback) {
var usbDeviceList = new Array();
fs.readdir(deviceDir, function (error, file) {
if (error) {
callback(null, error);
} else {
// ...
callback(usbDeviceList, null);
};
});
}
Or wrap it in a promise, which is easier to maintain:
function readDeviceList() {
var usbDeviceList = new Array();
return new Promise((resolve, reject) => {
fs.readdir(deviceDir, function (error, file) {
if (error) {
reject(error);
} else {
// ...
resolve(usbDeviceList);
};
});
});
}
Usage:
// Callback
readDeviceList(function (usbDeviceList, error) {
if (error) {
// Handle error
} else {
// usbDeviceList is available here
}
});
// Promise
readDeviceList.then(function (usbDeviceList) {
// usbDeviceList is available here
}).catch(function (error) {
// Handle error
});
Upvotes: 1