Marcus Harting
Marcus Harting

Reputation: 75

Electron Dialog filePath "\\" to "/"?

I open an dialog in electron to select an folder and I want to read out the file path. But the result.filePaths gives me an filePath with \\ what is not workible for me, to read later the files in the folder. 😅

Result now:

"P:\\Social Media\\Soundboard\\Sounds"

Expected Result:

"P:/Social Media/Soundboard/Sounds"

Is it any way to convert it to "/"? 🤔

My code:

const dialog = require('electron').remote.dialog

dialog.showOpenDialog({
    properties: ['openDirectory', 'multiSelections']
}).then(result => { 

 //Get Selected Folders
 folderpath = result.filePaths
 console.log(folderpath)
});

Upvotes: 1

Views: 820

Answers (2)

dreamLo
dreamLo

Reputation: 1890

Here's how I develop electron apps to work on both unix and windows without any issues.

Instead of using the path module function, I extended the functionality by using the module below and call that instead. This will sanitize all paths and convert them to correct unix paths like '/var/path/file' or 'C:/path/file'.

Windows can actually work with unix paths for creating/reading/updating/moving files and folders.

export default {
  extname (file) {
    return path.extname(file)
  },

  resolve () {
    return this.sanitizePath(Array.from(arguments).join('/').replace('//', '/'))
  },

  normalize () {
    const file = this.resolve(...arguments)
    return this.sanitizePath(path.normalize(file))
  },

  basename (file, ext = '') {
    return this.sanitizePath(path.basename(file, ext))
  },

  dirname (file) {
    return this.sanitizePath(path.dirname(file))
  },

  relative (from, to) {
    return this.sanitizePath(path.relative(path.resolve(from), path.resolve(to)))
  },

  sanitizePath (absPath) {
    // fix windows separator
    return absPath.replaceAll(path.sep, '/')
  }
}

The only time I needed windows specific paths was with shell.moveItemToTrash(file) and for that I had to us this client side function

convertPathForWin (file, os = navigator.platform) {
    return (os.toLowerCase() === 'win32') ? file.replaceAll('/', '\\') : file
}

Upvotes: 1

BadPiggie
BadPiggie

Reputation: 6379

Windows uses \ to separate nested resources instead of /. But it supports both. If you still want to convert \\ to /. You can try the below method.

//Get Selected Folders
 folderpath = result.filePaths.replaceAll('\\', '/');
 console.log(folderpath);

Upvotes: 1

Related Questions