The Filesystem Aptitude provides the ability to interact with files on the system (including things reading, writing, and deleting).
Each Loop is provided with their own blank "working" directory for this Aptitude, which is what relative paths resolve to. Loops are free to do anything they want to any file/directory inside of this working directory.
Loops cannot access other Loops' working directories.
This working directory persists across Loop version updates.
Copy
Copies a file from one location to another.
import { filesystem } from'@oliveai/ldk';constSOURCE_PATH='/var/log/system.log';constDESTINATION_PATH='/Users/username/system.log';// Check to make sure the system log existsconstsystemLogExists=awaitfilesystem.exists(SOURCE_PATH);// Copy the system log to the user folderif (systemLogExists) {awaitfilesystem.copy(SOURCE_PATH,DESTINATION_PATH);}
dir
Returns all files in the specified directory.
import { filesystem } from'@oliveai/ldk';// Get all files in the /var/log directoryconstallLogs=awaitfilesystem.dir('/var/log');/*allLogs:[ { "name": "foo.txt", "size": 476, "mode": "-rw-r--r--", "modTime": "2021-10-18T12:46:16.234535644-04:00", "isDir": false }, { "name": "bar", "size": 96, "mode": "drwxr-xr-x", "modTime": "2021-09-19T05:25:54.491321266-04:00", "isDir": true }, ...]*/
exists
Return true if a file or directory exists at the specified location.
import { filesystem } from'@oliveai/ldk';// Check to make sure /var/log directory existsconstlogDirExists=awaitfilesystem.exists('/var/log');// logDirExists === true// Check to make sure /var/log/system.log file existsconstsysLogExists=awaitfilesystem.exists('/var/log/system.log');// sysLogExists === true// Check to make sure /var/log/fakeDirectory directory existsconstfakeDirExists=awaitfilesystem.exists('/var/log/fakeDirectory');// fakeDirExists === false
join
Join joins an array of path elements into a single path, separating them with an OS specific Separator. Empty elements are ignored. The result is cleaned. However, if the argument list is empty or all its elements are empty, Join returns an empty string. On Windows, the result will only be a UNC path if the first non-empty element is a UNC path.
import { filesystem } from'@oliveai/ldk';// Create path string for a local text file that works on both // Windows and Unix-based systemsconsttestDirectory=awaitfilesystem.join(['testDirectory','foo.txt']);// Windows: testDirectory == testDirectory\foo.txt// macOS: testDirectory == testDirectory/foo.txt
listenDir
Listen for changes to the contents of the directory.
import { filesystem } from'@oliveai/ldk';// The path of the directory where we want to listen for changesconstPATH='/var/log';// The callback function that runs when a change is detectedconstcallback= (fileEvent) => {// When a file or directory are added, opened, or updated:/* fileEvent: { "info": { "name": "foo.log", "size": 17, "mode": "-rwxr-xr-x", "modTime": "2021-10-27T22:14:24.596962-04:00", "isDir": false }, "action": "Create" or "Chmod" } */// When a file or directory is renamed or removed, it will fire off // the above fileEvent then another one afterward:/* fileEvent: { "action": "Rename" or "Remove", "name": "test.log" // old file name } */}constdirectoryListener=awaitfilesystem.listenDir(PATH, callback);// Cancel the listenerdirectoryListen.cancel();
listenFile
Listen for changes to a specific file.
import { filesystem } from'@oliveai/ldk';// The path of the file we want to listen to for changesconstPATH='/var/log/system.log';// The callback function that runs when a change is detectedconstcallback= (fileEvent) => {// When the file is opened or updated:/* fileEvent: { "info": { "name": "system.log", "size": 14592, "mode": "-rwxr-xr-x", "modTime": "2021-10-27T22:31:24.215811-04:00", "isDir": false }, "action": "Chmod" } */// When the file is renamed or removed, it will fire off // the above fileEvent then another one afterward:/* fileEvent: { "action": "Rename" or "Remove", "name": "system.log" // old file name } */}constfileListener=awaitfilesystem.listenFile(PATH, callback);// Cancel the listenerfileListener.cancel();
makeDir
Makes a directory at the specified location.
import { filesystem } from'@oliveai/ldk';// The path of the directory we want to createconstDESTINATION_PATH='/var/log/backups';// The permissions we want to give the directory, in octal format// https://www.linode.com/docs/guides/modify-file-permissions-with-chmod/constWRITE_MODE=0o750// Check to make sure the directory doesn't already existconstdirectoryExists=awaitfilesystem.exists(DESTINATION_PATH);if (!directoryExists) {awaitfilesystem.makeDir(DESTINATION_PATH,WRITE_MODE);}
move
Moves a file from one location to another.
import { filesystem } from'@oliveai/ldk';constSOURCE_PATH='/var/log/system.log';constDESTINATION_PATH='/Users/username/system.log';// Check to make sure the system log existsconstsystemLogExists=awaitfilesystem.exists(SOURCE_PATH);// Move the system log to the user folderawaitfilesystem.move(SOURCE_PATH,DESTINATION_PATH);
openWithDefaultApplication
Opens a file using the operating system's default tool for the extension provided in the path parameter, including directories.
Limited to the following file extensions: .txt, .xls, .xlsx, .csv, .pdf, .doc, .docx, .jpg, .jpeg, .png, .apng, .gif, .tif, .tiff, .bmp, .webp, .svg, and .ico
import { filesystem } from'@oliveai/ldk';// Open foo.txt in the loop directoryawaitfilesystem.openWithDefaultApplication('foo.txt')
readFile
Returns the contents of the specified file.
import { filesystem, network } from'@oliveai/ldk';// Path of the system log that we want to readconstFILE_PATH='/var/log/system.log';// Get the contents of the system log, returned as a Uint8ArrayconstencodedSysLog=awaitfilesystem.readFile(FILE_PATH);// Decode the contents to get the actual string valueconstdecodedSysLog=awaitnetwork.decode(encodedSysLog);// decodedSysLog === human readable string of system.log contents
remove
Removes a file/directory at the specified path.
import { filesystem } from'@oliveai/ldk';// Path of foo.txt in the local loop directoryconstFILE_PATH='foo.txt';// Delete foo.txtawaitfilesystem.remove(FILE_PATH);
import { filesystem } from'@oliveai/ldk';// foo.zip is in the local loop directory, and contains bar.txt// Unzip the contents of foo.zip to the directory "baz"awaitfilesystem.unzip('foo.zip','baz');constunzipSuccessful=awaitfilesystem.exists('baz/bar.txt');// unzipSuccessful === true
workDir
Get the Loop's working directory.
import { filesystem } from'@oliveai/ldk';// Get the full path to the loop's working directoryconstloopPath=awaitfilesystem.workDir();// macOS: loopPath === /Users/username/Library/Application Support/Olive Helps/secureloopWork/123456-unique-loop-id// Windows: loopPath === C:\Users\username\AppData\Roaming\Olive Helps\secureloopWork\123456-unique-loop-id
writeFile
WriteFile writes data to a file and is designed for both synchronous and asynchronous operation.
import { filesystem } from'@oliveai/ldk';// The content we'll be putting in the fileconstFILE_CONTENT='Some test text to put in a file';// The path in the loop directory for the fileconstDIRECTORY='foo';constFILE_NAME='bar.txt';constfilePath=awaitfilesystem.join([DIRECTORY,FILE_NAME]);// The permissions we want to give the file, in octal format// https://www.linode.com/docs/guides/modify-file-permissions-with-chmod/constFILE_PERMISSIONS=0o750;// The write operations to choose from while writing the fileconst { overwrite,append } =filesystem.WriteOperation;constwriteFileParams= { data:FILE_CONTENT, path: filePath, writeMode:FILE_PERMISSIONS, writeOperation: overwrite};awaitfilesystem.writeFile(writeFileParams);
In this example, we use the Clipboard aptitude to listen for you copying text to the clipboard, and automatically append it to a file in the local Loop directory. This could be useful to pair with a button/toggle in a Whisper, where this capability can be enabled before rapidly copying several items, pasted into the file, then toggle it off when finished.
import { filesystem, clipboard } from'@oliveai/ldk';constFILE_NAME='clipboardPastes.txt';constbaseWriteFileParams= { data:'', path:FILE_NAME, writeMode:0o755, writeOperation:filesystem.WriteOperation.append,};// Include clipboard events that happen while the // Olive Helps window is in focusconstINCLUDE_OLIVE_HELPS_EVENTS=true;clipboard.listen(INCLUDE_OLIVE_HELPS_EVENTS, (clipboardText) => {constwriteFileParams= {...baseWriteFileParams, data: clipboardText +'\n', };awaitfilesystem.writeFile(writeFileParams);});
Listen to directory for zip files and automatically unzip then delete zip file. This could be customized with the Dropzone component to select the exact folder to monitor for ZIP files.
import { filesystem } from'@oliveai/ldk';// Here we're declaring the downloads folder, but this can be chosen by the// user using the Dropzone component in a WhisperconstdownloadsFolder='/Users/username/Downloads';filesystem.listenDir(downloadsFolder,async (fileEvent) => {const { action,info } = fileEvent;// If a file was "created" in this directoryif (action ==='Create'&& info) {const { name: fileName } = info;// If the file is a zip file, unzip itif (fileName.endsWith('.zip')) {constzipFilePath=awaitfilesystem.join([downloadsFolder, fileName]);// Unzip the contents to the Downloads folderawaitfilesystem.unzip(zipFilePath, downloadsFolder);// Delete the zip file after unzippingawaitfilesystem.remove(zipFilePath); } }});
To use the Filesystem Aptitude, use the following permissions outline in your package.json under the ldk object.
Please see our Permissions page for more information.
Each value can either refer to an exact absolute path or use a glob wildcard. The only supported wildcards are ** and *, and can be used anywhere in the path.
Relative file paths can be accessed without specifying them in the permissions list.
Examples
{"ldk": {"permissions": {"filesystem": {"pathGlobs": [ {// Provides access to all files in the /tmp directory that have a .txt extension."value":"/tmp/*.txt" }, {// Provides access to all directories and files under the /tmp directory."value":"/tmp/**" }, {// Provides access to all files with .txt extensions in the /tmp directory or any of its subdirectories."value":"/tmp/**/*.txt" }, {// Provides access to all files with .txt extensions in any subdirectory of /tmp."value":"/tmp/*/*.txt" } ] } } }}