Alex Hawking
Alex Hawking

Reputation: 1245

Get path of associated file when opened on double click Electron builder

Information:

I am trying to make an app that edits .txt files. I want to get the path of the text file when it is opened with the application (i.e. the user chooses to open the .txt with my app). I have included the following in the build of my package.json:

"fileAssociations": [
    {
        "name": "Text Files",
        "description": "Plain Text File",
        "ext": [
            "txt"
        ]
    }
],

This makes the application open with the file however how do I get the path of the file that was used to open the app. I know I have to do something with a process.argv however I have no idea how to use this. I have tried the below with no success:

ipcMain.on('get-file-data', function(event) {
    var data = null;
    if (process.platform == 'win32' && process.argv.length >= 2) {
        var openFilePath = process.argv[1];
        console.log(data)
        win.webContents.send('openFile', openFilePath)
    }
});

How can I get the path of the file?

Upvotes: 2

Views: 1375

Answers (2)

Alex Hawking
Alex Hawking

Reputation: 1245

I managed to get the path with the following:

const { remote } = require('electron');

console.log(remote.process.argv[1])

This returns the path of the file used to open the app!

Upvotes: 1

tpikachu
tpikachu

Reputation: 4854

This is the log of the whole process. As we can see here, the second argv is the path of the input file path. So process.argv[1] will be enough to the file path. Not sure why you can't get a path.

Maybe this comes from your ipc event listener. Which means the get-file-data is not fired correctly.

As you can see in this below image,I'm showing this process variable in this browser console. Here is how I exposed process variable to the renderer. But this is just for debug! Recommend not doing this in your production.

preload.js

process.once("loaded", () => {
    window.process = process;
});

main.js

mainWindow = new BrowserWindow({
    width: 1024,
    height: 728,
    minWidth: 800,
    minHeight: 750,
    webPreferences: {
        enableRemoteModule: true,
        preload: path.join(__dirname, "preload.js"),
    }
});

And you can use window.process or process on your renderer

enter image description here

Upvotes: 3

Related Questions