Expose an fs.exists over the context bridge

This commit is contained in:
Manav Rathi 2024-03-23 18:27:55 +05:30
parent 120edbbc65
commit a5c3aff54b
No known key found for this signature in database
4 changed files with 49 additions and 0 deletions

6
desktop/src/main/fs.ts Normal file
View file

@ -0,0 +1,6 @@
/**
* @file file system related functions exposed over the context bridge.
*/
import { existsSync } from "node:fs";
export const fsExists = (path: string) => existsSync(path);

View file

@ -10,6 +10,7 @@ import { ipcMain } from "electron/main";
import { appVersion } from "../services/appUpdater";
import { openDirectory, openLogDirectory } from "./general";
import { logToDisk } from "./log";
import { fsExists } from "./fs";
// - General
@ -40,4 +41,6 @@ export const attachIPCHandlers = () => {
// See: [Note: Catching exception during .send/.on]
ipcMain.on("logToDisk", (_, msg) => logToDisk(msg));
ipcMain.handle("fsExists", (_, path) => fsExists(path));
};

View file

@ -88,6 +88,13 @@ const openLogDirectory = (): Promise<void> =>
const logToDisk = (message: string): void =>
ipcRenderer.send("logToDisk", message);
/**
* Return true if there is a file or directory at the given
* {@link path}.
*/
const fsExists = (path: string): Promise<boolean> =>
ipcRenderer.invoke("fsExists", path);
// - FIXME below this
/* preload: duplicated logError */
@ -429,6 +436,11 @@ contextBridge.exposeInMainWorld("ElectronAPIs", {
skipAppUpdate,
muteUpdateNotification,
// - FS
fs: {
exists: fsExists,
},
// - Export
exists,
checkExistsAndCreateDir,

View file

@ -50,6 +50,34 @@ export interface ElectronAPIsType {
*/
logToDisk: (message: string) => void;
/**
* A subset of filesystem access APIs.
*
* The renderer process, being a web process, does not have full access to
* the local filesystem apart from files explicitly dragged and dropped (or
* selected by the user in a native file open dialog).
*
* The main process, however, has full filesystem access (limited only be an
* OS level sandbox on the entire process).
*
* When we're running in the desktop app, we want to better utilize the
* local filesystem access to provide more integrated features to the user -
* things that are not currently possible using web technologies. For
* example, continuous exports to an arbitrary user chosen location on disk,
* or watching some folders for changes and syncing them automatically.
*
* Towards this end, this fs object provides some generic file system access
* functions that are needed for such features. In addition, there are other
* feature specific methods too in the top level electron object.
*/
fs: {
/**
* Return true if there is a file or directory at the given
* {@link path}.
*/
exists: (path: string) => Promise<boolean>;
};
exists: (path: string) => boolean;
checkExistsAndCreateDir: (dirPath: string) => Promise<void>;
saveStreamToDisk: (