fs.readdir inside ipcMain.handle does not return

it always returns undefined, any idea please? i need the return inside fs.reddir but relative to ipcMain

//main

ipcMain.handle('pegaDirRomSalvo', async (event, argx=0) => {
  fs.readFile('dataCR.txt', 'utf8', function (err,data) {

    if (err) {return '0'}
    fs.readdir(data, (err, files) => {
          if (err) {throw err;}
          return [data,files] //<-------- not going
    })
   
  })
})


//render

ipcRenderer.invoke('pegaDirRomSalvo',a=0).then((result)=>{
         document.getElementById('divCaminho').innerText = result[0]
})

Answer

You need to use event.sender.send to trigger another call from the main to the renderer process to return the result, where the last will listen to it using ipcRenderer.on. Here is a sample solution:

renderer:

const { ipcRenderer } = require('electron');
ipcRenderer.invoke('pegaDirRomSalvo', a=0);
ipcRenderer.on('FILES_LIST_FETCHED', (event, result) => {
     console.log(result);
     document.getElementById('divCaminho').innerText = result[0]
});

main:

const { ipcMain } = require('electron');
ipcMain.handle('pegaDirRomSalvo', async (event, argx=0) => {
     fs.readFile('dataCR.txt', 'utf8', function (err,data) {
          if (err) { return '0'; }
          fs.readdir(data, (err, files) => {
               if (err) {throw err;}
               event.sender.send('FILES_LIST_FETCHED', [data, files]);
          })
     });
});

You can do the same for returning the error details if you want.

EDIT: This technique is usually used when sending the renderer call using ipcRenderer.send and receiving it on the main process using ipcMain.on.

Leave a Reply

Your email address will not be published. Required fields are marked *