javascriptnode.jselectronasar

Electron - How to point to a path outside asar generated app


I have an electron app that will be executed using a node script that will run a cron once a week. I need to execute a python file that is in a folder named dependencies and it's created when I do the build using npm run electron:build. I'm not using the installer of the app but I'm running the exe file that is inside the win-unpacked folder that will contain the app. If I run dev mode all work fine, the file with the python script is executed without problem, but in production app the application will not recognize the dependencies folder also if it exist. How I can point correctly to the folder that is outside the asar created from the build process?

ipcMain.on('saveExtractionData', (event, ...args) => {
//Other code stuff ...  
    if( !fs.existsSync( outputDir ) ){
        console.log(`Output folder not exist. Creating folder at: ${outputDir}`);
        fs.mkdir( outputDir, (err) => {
            if( err ){
                throw err
            }
// The file and the folder exists but electron seems not recognize it with this path
            fs.readFile('dependencies/cleaner.py', (error, buffer) => {
                if(error){
                    throw error
                }
                fs.writeFileSync( path.join(outputDir, 'cleaner.py'), buffer)
            })
            fs.writeFile( path.join(outputDir, `${filename}.xlsx`), fileBuffer, (error) => {
                if( error ){
                    throw error
                }
                console.log(`Writing file ${filename}.xlsx into ${outputDir} folder...`);
                event.sender.send('resetExtractionData')
            })
        })
    } else { 
        fs.writeFile( path.join(outputDir, `${filename}.xlsx`), fileBuffer, (error) => {
            if( error ){
                console.log(error)
                throw error
            }
            console.log(`Writing file ${filename}.xslx into ${outputDir} folder...`)
            event.sender.send('resetExtractionData')
        })
    }
})

Solution

  • Electron's app (https://www.electronjs.org/docs/latest/api/app) Module can be your friend here. It contains a helper function called getPath() which returns various paths.

    In your case app.getPath('exe') would be the best fit as it returns the name and path to your app's executable. If you combine that with path.parse().dir you can retrieve the actual path.

    For example:

    const app = require('electron');
    const path = require('path');
    const fs = require('fs');
    
    fs.readFile(path.join(path.parse(app.getPath('exe')).dir, 'dependencies', 'cleaner.py'), (error, buffer) => {});