I want to load images from paths given by the user (possibly modify them) and to display them using electron.
I used to use Electron many years ago and then it was quite easy since access to ‘fs’ node module was still unrestricted. Now, if I want to use ‘fs’ in the renderer I get error messages like this one:
Uncaught Error: Module “fs” has been externalized for browser compatibility. Cannot access “fs.existsSync” in client code.
So my solution was to load the file in the main process to a blob, create an URL for the blob and pass it to the renderer using IPC. This is a minimal example:
main.ts
export async function loadWebpFromFile(path: string) {
const fileContents = await fs.promises.readFile(path, null);
const webpImage = new Blob([fileContents], {
type: 'image/webp',
});
return URL.createObjectURL(webpImage);
}
ipcMain.handle(
'getWebpUrl',
(event: any, path: string) => loadWebpFromFile(path),
);
preload.ts
contextBridge.exposeInMainWorld('fromMain', {
getWebpUrl: async (path: string) => {
return ipcRenderer.invoke('getWebpUrl', path);
},
});
App.ts
const App = () => {
const [webpUrl, setWebpUrl] = useState<string>("");
useEffect(() => {
(async () => {
const webpUrl = await (window as any).fromMain.getWebpUrl ("C:\images\a.webp");
setWebpUrl(webpUrl);
})();
}, []);
return (
<div>
<h1>ElectroVite</h1>
<img src={webpUrl} />
</div>
);
};
But I get the following error in the console:
Not allowed to load local resource: blob:nodedata:985f076a-f83d-4fb8-82e3-5826401afed1 localhost/:1
So how can I exactly access this URL. Why is it even blocked? Or perhaps should I use a completely different approach?
The example is based on the following Typescript-React-Vite boilerplaite:
https://github.com/guasam/electrovite-react