I am learning how to create an Electron react app and i want to use fs.readFileSync() in a renderer file (i'm trying to get it to work with the amazon rekognition api). I used contextBridge and ipcRenderer to expose the function. However, i keep getting the TypeError: Cannot read properties of undefined error when i click the button that tries to trigger window.myFS.readFile().
If anyone is able to help, I would really appreciate if you could let me know what I'm doing wrong! Thank you so much!
The code I used are below:
main.js
const {app, BrowserWindow, ipcMain} = require('electron');
const url = require('url');
const path = require('path');
const fs = require('fs');
function createMainWindow() {
const mainWindow = new BrowserWindow({
title: 'Electron React App',
width: 600,
height: 400,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
});
mainWindow.loadURL('http://localhost:3000');
return mainWindow
}
app.whenReady().then(() => {
ipcMain.handle("readFile", (filePath)=>{return fs.readFileSync(filePath)})
createMainWindow()
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
preload.js
const {contextBridge, ipcRenderer} = require("electron");
contextBridge.exposeInMainWorld(
"myFS", {
readFile:(filePath) => {
ipcRenderer.invoke("readFile", filePath);
}
}
);
Work.js
import React from "react";
const Rekognition = require("aws-sdk");
export default function Work() {
return (
<div>
<button id="apibutton" onClick={credentials}>
Try Amazon Rekognition!
</button>
</div>
)
}
function credentials() {
const rekognition = new Rekognition.Rekognition({
region: 'ap-southeast-1'
});
rekognition.detectFaces({
Attributes: ["ALL"],
Image: {
Bytes: window.myFS.readFile("./download.jpg")
}
}, (err, data) => {
if (err) {
console.log(err,err.stack);
} else {
console.log(data.json());
}
})
}
Error
Cannot read properties of undefined (reading 'readFile')
TypeError: Cannot read properties of undefined (reading 'readFile')
at credentials (http://localhost:3000/static/js/bundle.js:481:26)
at HTMLUnknownElement.callCallback (http://localhost:3000/static/js/bundle.js:38425:18)
at Object.invokeGuardedCallbackDev (http://localhost:3000/static/js/bundle.js:38469:20)
at invokeGuardedCallback (http://localhost:3000/static/js/bundle.js:38526:35)
at invokeGuardedCallbackAndCatchFirstError (http://localhost:3000/static/js/bundle.js:38540:29)
at executeDispatch (http://localhost:3000/static/js/bundle.js:42683:7)
at processDispatchQueueItemsInOrder (http://localhost:3000/static/js/bundle.js:42709:11)
at processDispatchQueue (http://localhost:3000/static/js/bundle.js:42720:9)
at dispatchEventsForPlugins (http://localhost:3000/static/js/bundle.js:42729:7)
at http://localhost:3000/static/js/bundle.js:42889:16
Update I realise the error only appears when I am running the app on local browser. It works fine when I run it on electron desktop app.