Electron - fs.readdir callback sometimes doesn't execute on reload

Viewed 679

About 30% of the time my electron app does not execute the fs.readdir callback after I've reloaded the window that contains that script. When I open the application with electron ., the issue never occurs, it only ever occurs after I've reloaded the window.

I've tried adding a setTimeout of 5 seconds before executing fs.readdir, however this didn't change anything. Additionally, after the first time fs.readdir is run, all proceeding fs.readdir callbacks are never executed unless done immediately afterwards or if the window has never been reloaded before.

Anyone know a why this occurs and a solution?

mainWindow.js:

const fs = require('fs')

// read all files in "images" directory
function readDirectory(){
    fs.readdir('images', (e, files) => {
        // On error, show and return error
        if(e) return console.error(e);
        
        console.log(files)
    });
}

readDirectory()

main.js:

const electron = require('electron')
const path = require('path')
const {app, BrowserWindow, Menu} = electron

process.env.NODE_ENV = 'development'

let mainWindow
let mainMenu

function createMainWindow(){
    // Create mainWindow
    mainWindow = new BrowserWindow({
        icon:'icon.png',
        webPreferences:{
            nodeIntegration:true,
            fullscreen: true
        }
    })
    // Load html file
    mainWindow.loadFile('mainWindow.html')

    // Main menu
    mainMenu = Menu.buildFromTemplate(mainMenuTemplate)
    // Set main menu
    Menu.setApplicationMenu(mainMenu)


    // Garbage handling
    mainWindow.on('close',()=>{
        mainWindow = null
        mainMenu = null // idk if necessary
    })

    if (process.env.NODE_ENV !== 'production'){
        mainWindow.webContents.openDevTools()
    }
}

app.on('ready',e=>{
    createMainWindow()
})

const mainMenuTemplate = [
    {
        role:'reload',
        accelerator:'cmdorctrl+r',
    }
]

Also, sometimes the content is read but then it seems like it disappears. Vid: https://imgur.com/a/qZjwSBi

1 Answers
Related