How to get a File object from open-file events?


My electron app handles the open-file event, which is sent when a file is dragged onto the app’s icon in the Finder (Mac OS). The handler looks like this (below). The path argument is a string. So far, so good.

app.on('will-finish-launching', function() {
       app.on('open-file', function(ev, path) {...});

What I really want, however, is not to be given a pathname string, but a File object, so I can pass it to a FileReader which is useful in many ways. For example, I’d like to use exif-parser to read EXIF tags from a JPEG file. File objects seem to be the preferred model for files received via drag-and-drop or <INPUT type="file"> elements.

OK, so I have a pathname string from drag-and-drop onto my app icon, but now I can’t seem to find any constructor that creates a File from an arbitrary path string, since that would violate security. The user needs to click on or upload a file in order to create a File.

I have found a constructor that lets me create a File by passing it the file contents as well as the name. This misses the whole point of creating a File just so I can pass it to a FileReader.

I have found this, but it doesn’t work. It’s not the same kind of File object so I can’t pass it to FileReader. (It sure seems like it should be the same File API as the one you get from window.File). Also, this only works in the main process, not the renderer process:

var FileAPI = require('file-api');
var File = FileAPI.File;
var file = new File(path);

Wouldn’t it be better for open-file to pass the reference as a File rather than a string? Or at least make this an option?

And what is the best workaround? How do I construct a File object in electron that references the bits on disk located by a pathname string?




Did you end up finding a solution to this? In the same situation myself currently…


I don’t think I ever did, sorry. I don’t think I was able to get what I need from electron, and I moved on to other projects. I would love to know the answer, still.


Solution (what I am using anyway, not sure if it is the optimal way):

  1. Use the fs module to readFile as a base64 string
  2. Send the base64 string over via IPC
  3. Within React (in my case), convert the base64 string into a File object…