at first i need to say im pretty new to electron and node.js.
What i am doing is im trying to send an array with some directory data to my browser and this asynchronous (Error: array is empty).
The Problem should be my function 'scanDirectories(path)'. If i make it non recursive (scanDirectories(res) -> only return res) it works pretty fine for 1 level directories, but recursive it doesnt.
So i think i need to do it like my function above with returning a new promise? I tried it but can´t figure out how it works or my syntax should be.
Hope you can help me.
Simon
main.js:
calling function from ipcmain
ipcMain.on('fileTree', (event, arg) => {
let fileDirectory = helperFile.getDirectories(arg);
fileDirectory.then(function(result) {
event.reply('fileTree', result);
}, function(err) {
console.log(err);
})
})
files.js
const { readdir } = require('fs').promises;
const resolvePath = require('path').resolve;
module.exports = {
getDirectories: async function(path) {
return new Promise(function (resolve, reject) {
try {
resolve(scanDirectories(path));
} catch {
reject('Error');
}
});
}
};
async function scanDirectories(path) {
const dirents = await readdir(path, {withFileTypes: true});
const files = dirents.map((dirent) => {
const res = resolvePath(path, dirent.name);
return dirent.isDirectory() ? scanDirectories(res) : res;
});
return Array.prototype.concat(...files);
}