require('uxp').storage
Entry
An Entry is the base class for File and Folder. You'll typically never instantiate an Entry directly, but it provides the common fields and methods that both File and Folder share.
Entry(name, provider, id)
Creates an instance of Entry.
***isEntry : Boolean
Indicates that this instance is an Entry. Useful for type-checking.
Example
if (something.isEntry) {
return something.getMetadata();
}
isFile : Boolean
Read only Indicates that this instance is not a File. Useful for type- checking.
Example
if (!anEntry.isFile) {
return "This entry is not a file.";
}
isFolder : Boolean
Read only Indicates that this instance is not a folder. Useful for type- checking.
Example
if (!anEntry.isFolder) {
return "This entry is not a folder.";
}
name : String
Read only The name of this entry. Read-only.
Example
console.log(anEntry.name);
provider : FileSystemProvider
Read only The associated provider that services this entry. Read-only.
Example
if (entryOne.provider !== entryTwo.provider) {
throw new Error("Providers are not the same");
}
url : String
Read only The url of this entry. You can use this url as input to other entities of the extension system like for eg: set as src attribute of a Image widget in UI. Read-only.
Example
console.log(anEntry.url);
nativePath : String
Read only The platform native file-system path of this entry. Read-only
Example
console.log(anEntry.nativePath);
toString()
Returns the details of the given entry like name, type and native path in a readable string format.
Returns: String
copyTo(folder, options)
Copies this entry to the specified folder.
Returns: Promise<File | Folder>
Throws:
EntryExistsif the attempt would overwrite an entry andoverwriteisfalsePermissionDeniedif the underlying file system rejects the attemptOutOfSpaceif the file system is out of storage space
Folder*Booleanfalsetrue, allows overwriting existing entriesBooleanfalsetrue, allows copying the folderExample
await someFile.copyTo(someFolder);
Example
await someFile.copyTo(someFolder, {overwrite: true});
Example
await someFolder.copyTo(anotherFolder, {overwrite: true, allowFolderCopy: true});
moveTo(folder, options)
Moves this entry to the target folder, optionally specifying a new name.
Returns: Promise<void>
Folder*Booleanfalsetrue allows the move to overwrite existing filesStringExample
await someFile.moveTo(someFolder);
Example
await someFile.moveTo(someFolder, {overwrite: true});
Example
await someFolder.moveTo(anotherFolder, {overwrite: true});
Example
await someFile.moveTo(someFolder, {newName: 'masterpiece.txt'})
Example
await someFile.moveTo(someFolder, {newName: 'novel.txt', {overwrite: true})
delete()
Removes this entry from the file system. If the entry is a folder, all the contents will also be removed.
Returns: Promise<number> - the number is 0 if succeeded, otherwise throws an Error
Example
await aFile.delete();
getMetadata()
Returns this entry's metadata.
Returns: Promise<EntryMetadata>
Example
const metadata = aFile.getMetadata();
EntryMetadata
Metadata for an entry. It includes useful information such as:
- size of the file (if a file)
- date created
- date modified
- name
You'll not instantiate this directly; use Entry#getMetadata to do so.
name : String
The name of the entry.
size : number
The size of the entry, if a file. Zero if a folder.
dateCreated : Date
The date this entry was created.
dateModified : Date
The date this entry was modified.
isFile : Boolean
Indicates if the entry is a file
isFolder : Boolean
Indicates if the entry is a folder
File
Represents a file on a file system. Provides methods for reading from and writing to the file. You'll never instantiate a File directly; instead you'll get access via a localFileSystem.
isFile
Indicates that this instance is a file.
Example
if (anEntry.isFile) {
await anEntry.read();
}
mode : Symbol
Indicates whether this file is read-only or read-write. See readOnly and readWrite.
Example
if (aFile.mode === modes.readOnly) {
throw new Error("Can't write to a file opened as read-only.");
}
read(options)
Reads data from the file and returns it. The file format can be specified with the format option. If a format is not supplied, the file is assumed to be a text file using UTF8 encoding.
Returns: Promise<(String\|ArrayBuffer)> - the contents of the file
anyExample
const text = await myNovel.read();
Example
const data = await myNovel.read({format: formats.binary});
write(data, options)
Writes data to a file, appending if desired. The format of the file is controlled via the format option, and defaults to UTF8.
Returns: Promise<number> - the length of the contents written to the file
Throws:
FileIsReadOnlyif writing to a read-only fileOutOfSpaceIf writing to the file causes the file system to exceed the available space (or quota)
String | ArrayBufferanyBooleanfalsetrue, the data is written to the end of the fileExample
await myNovel.write("It was a dark and stormy night.\n");
await myNovel.write("Cliches and tropes aside, it really was.", {append: true});
Example
const data = new ArrayBuffer();
await aDataFile.write(data, {format: formats.binary});
isFile(entry)
Determines if the entry is a file or not. This is safe to use even if the entry is null or undefined.
Returns: Boolean - if true, the entry is a file.
anyFileSystemProvider
Provides access to files and folders on a file system. You'll typically not instantiate this directly; instead you'll use an instance of one that has already been created for you by UXP.
isFileSystemProvider : Boolean
Indicates that this is a FileSystemProvider. Useful for type-checking.
supportedDomains : Array<Symbol>
An array of the domains this file system supports. If the file system can open a file picker to the user's documents folder, for example, then userDocuments will be in this list.
Example
if (fs.supportedDomains.contains(domains.userDocuments)) {
console.log("We can open a picker to the user's documents.")
}
getFileForOpening(options)
Gets a file (or files) from the file system provider for the purpose of opening them. Files are read-only.
Multiple files can be returned if the allowMultiple optionistrue`.
Returns: Promise<File|Array<File>> based on allowMultiple. Return empty if no file was selected.
*SymbolArray<String>[".*"]File | FolderBooleanfalseExample
const folder = await fs.getFolder({initialDomain = domains.userDocuments});
const file = await fs.getFileForOpening({initialLocation = folder});
if (!file) {
// no file selected
return;
}
const text = await file.read();
Example
const files = await fs.getFileForOpening({allowMultiple: true, types: fileTypes.images});
if (files.length === 0) {
// no files selected
}
getFileForSaving(suggestedName, options)
Gets a file reference suitable for read-write. Displays a file picker to select a location to "Save" the file.
If the act of writing to the file would overwrite it, the file picker will prompt the user to confirm before returning a result to you.
Returns: Promise<File> - returns the selected file, or null if no file were selected.
Stringoptions.types is not defined.ObjectSymbolArray<String>Example
const file = await fs.getFileForSaving("output.txt", { types: [ "txt" ]});
if (!file) {
// file picker was cancelled
return;
}
await file.write("It was a dark and stormy night");
getFolder(options)
Gets a folder from the file system via a folder picker dialog. The files and folders within can be accessed via Folder#getEntries. Any files within are read-write.
If the user dismisses the picker, null is returned instead.
Returns: Promise<Folder | null> - the selected folder or null if no folder is selected.
anySymbolExample
const folder = await fs.getFolder();
const myNovel = (await fs.getEntries()).filter(entry => entry.name.indexOf('novel') > 0);
const text = await myNovel.read();
getTemporaryFolder()
Returns a temporary folder. The contents of the folder will be removed when the extension is disposed.
Returns: Promise<Folder>
Example
const temp = await fs.getTemporaryFolder();
getDataFolder()
Returns a folder that can be used for extension's data storage without user interaction. It is persistent across host-app version upgrades.
Returns: Promise<Folder>
getPluginFolder()
Returns an plugin's folder – this folder and everything within it are read only. This contains all the Plugin related packaged assets.
Returns: Promise<Folder>
getFsUrl(entry)
Returns the fs url of given entry.
Returns: String
EntrygetNativePath(entry)
Returns the platform native file system path of given entry.
Returns: String
EntrycreateSessionToken(entry)
Returns a token suitable for use with certain host-specific APIs (such as Photoshop). This token is valid only for the current plugin session. As such, it is of no use if you serialize the token to persistent storage, as the token will be invalid in the future.
Note: When using the Photoshop DOM API, pass the instance of the file instead of a session token -- Photoshop will convert the entry into a session token automatically on your behalf.
Returns: String - the session token for the given entry
EntryExample
const fs = require('uxp').storage.localFileSystem;
let entry = await fs.getFileForOpening();
let token = fs.createSessionToken(entry);
let result = await require('photoshop').action.batchPlay([{
_obj: "open",
"target": {
_path: token, // Rather than a system path, this expects a session token
_kind: "local",
}
}], {});
getEntryForSessionToken(token)
Returns the file system Entry that corresponds to the session token obtained from createSessionToken. If an entry cannot be found that matches the token, then a Reference Error: token is not defined error is thrown.
Returns: Entry - the corresponding entry for the session token
StringcreatePersistentToken(entry)
Returns a token suitable for use with host-specific APIs (such as Photoshop), or for storing a persistent reference to an entry (useful if you want to only ask for permission to access a file or folder once). A persistent token is not guaranteed to last forever -- certain scenarios can cause the token to longer work (including moving files, changing permissions, or OS-specific limitations). If a persistent token cannot be reused, you'll get an error at the time of use.
Returns: Promise<String> - the persistent token for the given entry
EntryExample
const fs = require('uxp').storage.localFileSystem;
let entry = await fs.getFileForOpening();
let token = await fs.createPersistentToken(entry);
localStorage.setItem("persistent-file", token);
getEntryForPersistentToken(token)
Returns the file system Entry that corresponds to the persistent token obtained from createPersistentToken. If an entry cannot be found that matches the token, then a Reference Error: token is not defined error is thrown.
Note: retrieving an entry for a persistent token does not guarantee that the entry is valid for use. You'll need to properly handle the case where the entry no longer exists on the disk, or the permissions have changed by catching the appropriate errors. If that occurs, the suggested practice is to prompt the user for the entry again and store the new token.
Returns: Promise<Entry> - the corresponding entry for the persistent token
StringExample
const fs = require('uxp').storage.localFileSystem;
let entry, contents, tries = 3, success = false;
while (tries > 0) {
try {
entry = await fs.getEntryForPersistentToken(localStorage.getItem("persistent-file"));
contents = await entry.read();
tries = 0;
success = true;
} catch (err) {
entry = await fs.getFileForOpening();
localStorage.setItem("persistent-token", await fs.createPersistentToken(entry));
tries--;
}
}
if (!success) {
// fail gracefully somehow
}
isFileSystemProvider(fs)
Checks if the supplied object is a FileSystemProvider. It's safe to use even if the object is null or undefined. Useful for type checking.
Returns: Boolean - If true, the object is a file system provider
anyFolder
Represents a folder on a file system. You'll never instantiate this directly, but will get it by calling FileSystemProvider.getTemporaryFolder, FileSystemProvider.getFolder, or via Folder.getEntries.
isFolder
Indicates that this instance is a folder. Useful for type checking.
getEntries()
Returns an array of entries contained within this folder.
Returns: Promise<Array<Entry>> - The entries within the folder.
Example
const entries = await aFolder.getEntries();
const allFiles = entries.filter(entry => entry.isFile);
createEntry(name, options)
Creates an entry within this folder and returns the appropriate instance.
Returns: Promise<File | Folder> the created entry
StringanySymboltypes.fileBooleanfalsetrue, the create attempt can overwrite an existing fileExample
const myNovel = await aFolder.createEntry("mynovel.txt");
Example
const catImageCollection = await aFolder.createEntry("cats", {type: types.folder});
createFile(name, options)
Creates a File Entry object within this folder and returns the appropriate instance. Note that this method just create a file entry object and not the actual file on the disk. The file actually gets created when you call for eg: write method on the file entry object.
Returns: Promise<File> - the created file entry
StringanyBooleanfalsetrue, the create attempt can overwrite an existing fileExample
const myNovelTxtFile = await aFolder.createFile("mynovel.txt");
createFolder(name)
Creates a Folder within this folder and returns the appropriate instance.
Returns: Promise<Folder> - the created folder entry object
StringExample
const myCollectionsFolder = await aFolder.createFolder("collections");
getEntry(filePath)
Gets an entry from within this folder and returns the appropriate instance.
Returns: Promise<File | Folder> the fetched entry.
StringExample
const myNovel = await aFolder.getEntry("mynovel.txt");
renameEntry(entry, newName, options)
Renames an entry to a new name.
Returns: Promise<void>
EntryStringanyBooleanfalsetrue, renaming can overwrite an existing entryExample
await myNovels.rename(myNovel, "myFantasticNovel.txt");
isFolder ⇒ Boolean
Checks if an entry is a folder. Safe to use if entry might be null or undefined. Useful for type checking.
Returns: Boolean - if true, the entry is a folder
anyFileSystem
UXP Provides Node.js style file system API, FSAPI. Unlike Entry based File or Folder classes, these methods can directly access a local file or folder with path or file descriptor. The starting point of a path in the native filesystem depends on the scheme. UXP supports plugin-specific storage schemes, such as "plugin:", "plugin-data:", and "plugin-temp:", as well as a native "file:" scheme for the path parameter.<br/> Note1: UWP(Universal Windows Platform) has the strict File access permissions, and UXP FSAPI may have access issues with anonymous filepaths. So, XD does not support this feature for compatibility across platforms.<br/> Note2: The native layer of UXP FSAPI is based on libUV except UWP powered features, such as FilePicker and Drag&Drop on Win10 XD.
readFile(path, options, callback)
Reads data from the path asynchronously. The file format can be specified with the encoding options. If an encoding is not supplied, the file is assumed to be a binary format.
Returns: Promise<String|ArrayBuffer> - the contents of the file
StringanyStringfunctionExample
const data = await fs.readFile("plugin-data:/binaryFile.obj");
Example
const text = await fs.readFile("plugin-data:/textFile.txt", {encoding: "utf-8"});
readFileSync(path, options)
Reads data from the path synchronously. The file format can be specified with the encoding options. If an encoding is not supplied, the file is assumed to be a binary format.
Returns: String | ArrayBuffer - the contents of the file
StringanyStringExample
const data = fs.readFileSync("plugin-data:/binaryFile.obj");
Example
const text = fs.readFileSync("plugin-data:/textFile.txt", {encoding: "utf-8"});
writeFile(path, data, options, callback)
Writes data to the path asynchronously, appending if desired. The format of the file is controlled via the encoding option, and defaults to a binary format.
Returns: Promise<int> - the length of contents written to the file
StringString | ArrayBuffer | ArrayBufferViewanyStringfunctionExample
const bufLen = await fs.writeFile("plugin-data:/binaryFile.obj", new Uint8Array([1, 2, 3]));
Example
const strLen = await fs.writeFile("plugin-data:/textFile.txt", "It was a dark and stormy night.\n", {encoding: "utf-8"});
writeFileSync(path, data, options)
Writes data to a path synchronously, appending if desired. The format of the file is controlled via the encoding option, and defaults to a binary format.
Returns: int - the length of contents written to the file
StringString | ArrayBuffer | ArrayBufferViewanyStringExample
const bufLen = fs.writeFileSync("plugin-data:/binaryFile.obj", new Uint8Array([1, 2, 3]));
Example
const strLen = fs.writeFileSync("plugin-data:/textFile.txt", "It was a dark and stormy night.\n", {encoding: "utf-8"});
open(path, [flag], [mode], callback)
Opens or a creates a file asynchronously
Returns: Promise<int> - fd(file descriptor)
StringfunctionExample
const fd = await fs.open("plugin-data:/fileToRead.txt", "r");
close(fd, callback)
Closes a file descriptor asynchronously
Returns: int - 0 if succeeded, otherwise throws an Error
intfunctionExample
await fs.close(fd);
read(fd, buffer, offset, length, position, callback)
Reads data in chunks from the file it refers to the file descriptor
Returns: Promise<Object> - { bytesRead, buffer }
Throws:
Errorif invalid file descriptor is passed. if invalid parameter format or value is passed.
intArrayBufferintintintfunctionExample
const fileSize = 1024;
const buffer = new ArrayBuffer(fileSize);
const fd = await fs.open("plugin-data:/fileToRead.txt", "r");
let bytesReadInTotal = 0;
while (bytesReadInTotal < fileSize) {
const { bytesRead } = await fs.read(fd, buffer, bytesReadInTotal, 128, -1);
if (!bytesRead) {
break;
}
bytesReadInTotal += bytesRead;
}
await fs.close(fd);
write(fd, buffer, offset, length, position, callback)
Writes data in chunks to the file it refers to the file descriptor
Returns: Promise<Object> - { bytesWritten, buffer }
Throws:
Errorif invalid file descriptor is passed if invalid parameter format or value is passed
intArrayBufferintintintfunctionExample
const fd = await fs.open("plugin-data:/fileToWrite.txt", "w+");
const data = "It was a dark and stormy night.\n";
const srcBuffer = new TextEncoder().encode(data).buffer;
const { bytesWritten } = await fs.write(fd, srcBuffer, 0, data.length, 0);
await fs.close(fd);
lstat(path, callback)
Gets information asynchronously from a file or a folder of the path
Returns: Promise<Object> - see Stats class in Node.js Note: Some methods or properties may not be supportive for the return object due to the platform limitation
StringfunctionExample
const stats = await fs.lstat("plugin-data:/textFile.txt");
const isFile = stats.isFile();
lstatSync(path)
Gets information synchronously from a file or a folder of the path
Returns: Object - see Stats class in Node.js Note: Some methods or properties may not be supportive for the return object due to the platform limitation
StringExample
const stats = fs.lstatSync("plugin-data:/textFile.txt");
const birthTime = stats.birthtime;
rename(oldPath, newPath, callback)
Renames or moves, if required, the file from the oldPath to the newPath
Returns: Promise<int> - 0 if succeeded, otherwise throws an Error
StringStringfunctionExample
fs.rename("plugin-data:/oldName.txt", "plugin-temp:/newName.txt");
copyFile(srcPath, destPath, flags, callback)
Copies a file or a folder from the source path to the destination path
Returns: Promise<int> - 0 if succeeded, otherwise throws an Error
StringStringfunctionExample
const data = fs.copyFile("plugin-data:/copyFrom.txt", "plugin-temp:/copyTo.txt");
unlink(path, callback)
Deletes a name with the file it refers to asynchronously
Returns: Promise<int> - 0 if succeeded, otherwise throws an Error
StringfunctionExample
await fs.unlink("plugin-data:/fileToDelete.txt");
mkdir(path, callback)
Creates a directory of the path asynchronously
Returns: Promise<int> - 0 if succeeded, otherwise throws an Error
StringfunctionExample
await fs.mkdir("plugin-data:/newDir");
rmdir(path, callback)
Removes a directory asynchronously
Returns: Promise<int> - 0 if succeeded, otherwise throws an Error
StringfunctionExample
await fs.rmdir("plugin-data:/dirToRemove");
readdir(path, callback)
Reads a directory to list the containing files and directories asynchronously
Returns: Promise<Array<String>> - string array of containing files and directories in the path
StringfunctionExample
const paths = await fs.readdir("plugin-data:/dirToRead");
readdirSync(path)
Reads a directory to list the containing files and directories synchronously
Returns: Array<String> - string array of containing files and directories in the path
StringExample
const paths = fs.readdirSync("plugin-data:/dirToRead");
localFileSystem : LocalFileSystemProvider
errors : Errors
AbstractMethodInvocationError
Attempted to invoke an abstract method.
ProviderMismatchError
Attempted to execute a command that required the providers of all entries to match.
EntryIsNotAnEntryError
The object passed as an entry is not actually an Entry.
EntryIsNotAFolderError
The entry is not a folder, but was expected to be a folder.
EntryIsNotAFileError
The entry is not a file, but was expected to be.
NotAFileSystemError
The instance was expected to be a file system, but wasn't.
OutOfSpaceError
The file system is out of space (or quota has been exceeded)
PermissionDeniedError
The file system revoked permission to complete the requested action.
EntryExistsError
An attempt was made to overwrite an entry without indicating that it was safe to do so via overwrite: true.
FileIsReadOnlyError
An attempt was made to write to a file that was opened as read-only.
DomainNotSupportedError
Domain is not supported by the current FileSystemProvider instance.
InvalidFileNameError
The file name contains invalid characters
InvalidFileFormatError
Unsupported format type
DataFileFormatMismatchError
Data and Format mismatch
NotSupported
Not supported error
domains
Common locations that we can use when displaying a file picker.
userDesktop : Symbol
The user's desktop folder
userDocuments : Symbol
The user's documents folder
userPictures : Symbol
The user's pictures folder or library
userVideos : Symbol
The user's videos / movies folder or library
userMusic : Symbol
The user's music folder or library
appLocalData : Symbol
Local application data
appLocalLibrary : Symbol
Local application library
appLocalCache : Symbol
Local application cache directory (persistence not guaranteed)
appLocalShared : Symbol
Local application shared data folder
appLocalTemporary : Symbol
Local temporary directory
appRoamingData : Symbol
Roaming application data
appRoamingLibrary : Symbol
Roaming application library data
fileTypes
This namespace describes the various file type extensions that can used be used in some FS file open methods.
text : Array<String>
Text file extensions
images : Array<String>
Image file extensions
all : Array<String>
All file types
formats
This namespace describes the file content formats supported in FS methods like read and write.
utf8 : Symbol
UTF8 File encoding
binary : Symbol
Binary file encoding
modes
This namespace describes the file open modes. for eg: open file in read-only or both read-write
readOnly : Symbol
The file is read-only; attempts to write will fail.
readWrite : Symbol
The file is read-write.
types
This namespace describes the type of the entry. Whether file or folder etc.
file : Symbol
A file; used when creating an entity
folder : Symbol
A folder; used when creating an entity