How to get folder path using electron

Viewed 38212

I am very new to the electron. Can anyone suggest me how to get a local folder's relative path using the electron? JavaScript does not have that capability.

enter image description here

I have a Choose File button(see snapshot), so my question is that when I select a folder and click on the open button then it should return a whole directory path.

5 Answers

In Electron we can select the directory by specifying simple input element with type="file" and webkitdirectory attribute'. <input id="myFile" type="file" webkitdirectory /> and we can get the directory full path with the path property of File object document.getElementById("myFile").files[0].path

Following the official IPC tutorial worked for me

main process:

import {dialog, ipcMain} from 'electron'
function createWindow () {
  mainWindow = new BrowserWindow({/*Your electron window boilerplate*/})
  ipcMain.handle('dialog:openDirectory', async () => {
    const { canceled, filePaths } = await dialog.showOpenDialog(mainWindow, {
      properties: ['openDirectory']
    })
    if (canceled) {
      return
    } else {
      return filePaths[0]
    }
  })
}

preload script:

import {contextBridge, ipcRenderer} from 'electron'

contextBridge.exposeInMainWorld('myAPI', {
  selectFolder: () => ipcRenderer.invoke('dialog:openDirectory')
})

Now you can call the selectFolder method from your application code and get the user input.

window.myAPI.selectFolder().then(result=>{/* Do something with the folder path*/})

The solution for me was simply using all in lowercase, with a value true as string in my react component. No extra configuration was required.

Like so:

<input
    id="path-picker"
    type="file"
    webkitdirectory="true"
/>

Edit

It turns out that, as mentioned by @cbartondock, it will recursively look for files in the directory, which is not good!

I ended up using the required electron remote's dialog.

Related