fileSystem
The sos.fileSystem API groups together methods for low-level access to the file system. The File System API supports both internal and
external storage.
File System directory structure is PERSISTENT and is NOT automatically deleted through Applet Reload power action!
Applet Reload only deletes /data directory which is reserved for simplified Offline Cache API. Use
deleteFile() to clear the device storage file system.
Device File System Capabilities
| Capability | Description |
|---|---|
FILE_SYSTEM_INTERNAL_STORAGE | If device supports internal storage units |
FILE_SYSTEM_EXTERNAL_STORAGE | If device supports connecting external storage units |
FILE_SYSTEM_FILE_CHECKSUM | If device supports checksum for MD5 or CRC32 hash algorithms |
FILE_SYSTEM_LINK | If device supports creating hard links to files |
FILE_SYSTEM_CREATE_ARCHIVE | If device supports creating archives - zip |
FILE_SYSTEM_ARCHIVE_EXTRACT_INFO | If device supports extracting information about archive files |
If you want to check if the device supports this capability, use sos.display.supports().
Storing files permanently
To allow more low-level file operations, the applet SDK exposes the File System API. Files created using this API are permanent and are only removed on a factory reset or file system wipeout. The file system is also shared between all applets, which means you cannot rely on any file system structure on startup because a different applet on the device could have saved files you didn't expect. To mitigate this issue, create a directory for your applet and save all files inside it.
import sos from '@signageos/front-applet';
sos.onReady(async () => {
const storageUnits = await sos.fileSystem.listStorageUnits();
const rootPath = {
filePath: '', // Empty string is used as an absolute path instead of "/"
storageUnit: storageUnits.find((s) => !s.removable), // Find internal storage
};
// This will return files previous applets saved to the device
const files = await sos.fileSystem.listFiles(rootPath);
});
Methods
appendFile()
The appendFile() method appends string content to the file specified by filePath.
If the file does exist, it is created.
Only string can be appended to the file. If you want to append binary data, you have to convert it to a string first.
appendFile(filePath: IFilePath, contents: string): Promise<void>;
Params
| Name | Type | Required | Description |
|---|---|---|---|
filePath | IFilePath | Yes | The path to the file to be appended. |
contents | string | Yes | The content to be appended to the file. |
Return value
A promise that resolves when the content is appended successfully.
Possible errors
- Error If the parent directory does not exist.
- Error If the
filePathis a directory. - Error If the
filePathis not a valid object or does not containstorageUnitandfilePath. - Error If any error occurs during the append operation on the device.
Example
const filePath = {
storageUnit: internalStorageUnit,
filePath: 'path/to/file.txt',
};
const contents = 'This is the content to append to the file.';
await sos.fileSystem.appendFile(filePath, contents);
copyFile()
The copyFile() method creates a copy of file from sourceFilePath to destinationFilePath.
copyFile(sourceFilePath: IFilePath, destinationFilePath: IFilePath, options?: ICopyFileOptions): Promise<void>;
Params
| Name | Type | Required | Description |
|---|---|---|---|
sourceFilePath | IFilePath | Yes | The path to the file to be copied. |
destinationFilePath | IFilePath | Yes | The path where the file will be copied to. |
options | ICopyFileOptions | No | Options for copying the file. |
options.overwrite | boolean | No | If set to true, the method will overwrite the destination file if it already exists. |
Return value
A promise that resolves when the file is copied successfully.
Possible errors
- Error If the source file does not exist.
- Error If parent of the destination file path does not exist.
- Error If
optionsobject is not valid. - Error If any error occurs during the copy operation on the device.
Example
// Copy file from one directory to another and overwrite it if it already exists
const sourceFilePath = {
storageUnit: internalStorageUnit,
filePath: 'path/to/source/file.txt',
};
const destinationFilePath = {
storageUnit: internalStorageUnit,
filePath: 'path/to/destination/file.txt',
};
await sos.fileSystem.copyFile(sourceFilePath, destinationFilePath, { overwrite: true });
createArchive()
The createArchive() method creates an archive file from selected files and directories.
- Never start OR end the
filePathwith a slash -/. - It is a good practice to check if file exists -
exists()prior creating it
- This function is available only on Tizen devices.
- All files are added to the archive based on absolute path from root directory.
createArchive(archiveFilePath: IFilePath, archiveEntries: IFilePath[]): Promise<void>;
Params
| Name | Type | Required | Description |
|---|---|---|---|
archiveFilePath | IFilePath | Yes | The path where the archive file will be created. |
archiveEntries | IFilePath[] | Yes | An array of file paths to be included in the archive. |
Return value
A promise that resolves when the archive file is created successfully.
Possible errors
- Error If
archiveFilePathis not a valid object or does not containstorageUnitandfilePath. - Error If
archiveEntriesis not a valid array of objects. - Error If the parent directory of
archiveFilePathdoes not exist. - Error If any of the
archiveEntriesdo not exist or are directories. - Error If creating the archive file fails.
- Error If the platform does not support creating archive files.
Example
const archiveFilePath = {
storageUnit: internalStorageUnit,
filePath: 'path/to/archive.zip',
};
const archiveEntries = [
{
storageUnit: internalStorageUnit,
filePath: 'path/to/file1.txt',
},
{
storageUnit: internalStorageUnit,
filePath: 'path/to/file2.txt',
},
{
storageUnit: internalStorageUnit,
filePath: 'path/to/directory1',
},
];
await sos.fileSystem.createArchive(archiveFilePath, archiveEntries);
createDirectory()
The createDirectory() method create a new directory at specified path.
- Never start OR end the filePath with a slash -
/. - It is a good practice to check if directory exists -
isDirectory()prior creating it.
createDirectory(directoryPath: IFilePath): Promise<void>;
Params
| Name | Type | Required | Description |
|---|---|---|---|
directoryPath | IFilePath | Yes | The path where the new directory will be created. |
Return value
A promise that resolves when the directory is created successfully.
Possible errors
- Error If
directoryPathis not a valid object or does not containstorageUnitandfilePath. - Error If the directory already exists.
- Error If parent directory does not exist.
Example
const internalStorageUnit = (await sos.fileSystem.listInternalStorageUnits())[0];
const directoryPath = {
storageUnit: internalStorageUnit,
filePath: 'path/to/new/directory',
};
await sos.fileSystem.createDirectory(directoryPath);
deleteFile()
The deleteFile() method deletes the file specified by filePath.
deleteFile(filePath: IFilePath, recursive: boolean): Promise<void>;
Params
| Name | Type | Required | Description |
|---|---|---|---|
filePath | IFilePath | Yes | The path to the file or directory to be deleted. |
recursive | boolean | Yes | If set to true, the method will delete the directory and all its contents recursively. |
Return value
A promise that resolves when the file is deleted successfully.
Possible errors
- Error If
filePathis not a valid object or does not containstorageUnitandfilePath. - Error If the file does not exist or if
recursiveis set to false and the file path is a directory. - Error If deleting path does not exist.
- Error When is deleting directory and is not empty (not recursive).
Example
// Delete directory and all files inside
//// First check, if there is such a directory
if (await sos.fileSystem.exists({ storageUnit: internalStorageUnit, filePath: 'test-dir' })) {
// Delete the directory and all it's content recursively
await sos.fileSystem.deleteFile({ storageUnit: internalStorageUnit, filePath: 'test-dir' }, true);
}
// Delete file
//// First check, if there is such a file
if (await sos.fileSystem.exists({ storageUnit: internalStorageUnit, filePath: 'test-dir/downloaded-file.png' })) {
// Delete the file
await sos.fileSystem.deleteFile({ storageUnit: internalStorageUnit, filePath: 'test-dir/downloaded-file.png' }, false);
}
downloadFile()
The downloadFile() method download a file from sourceUri and saves it to the specified path. If the file already exists, the file will be
overwritten. Optionally, headers for the download request may be specified.
For every download request, our Core Apps makes HEAD request for content-length header on that downloaded file. It's due to determining if device has enough space to download the file.
Encoding
All downloads respect a standard of Encoding with optional compression of files. See Mozilla standard Accept Encoding and Content Encoding.
Download file method is always sending optional following headers:
Accept-Encoding: gzip
Accept-Encoding: compress
Accept-Encoding: deflate
Accept-Encoding: br
Accept-Encoding: identity
Accept-Encoding: *
If the server understands the Encoding standard, it compresses files using gzip algorithm before the files are sent to the client. If so, the response will contain the following headers:
Content-Encoding: gzip
Content-Encoding: compress
Content-Encoding: deflate
Content-Encoding: br
So the data communication is compressed under the hood. The client will automatically decompress data before it's saved to a specified location path. So from JS API point of view, there is no requirement to decompress data by itself.
The standard is supported on all following platforms:
- WebOS 3+
- Tizen 2.4+
- Brightsign
- Raspberry Pi
- Windows
downloadFile(filePath: IFilePath, sourceUri: string, headers?: IHeaders): Promise<void>;
Params
| Name | Type | Required | Description |
|---|---|---|---|
filePath | IFilePath | Yes | The path where the downloaded file will be saved. |
sourceUri | string | Yes | The URI of the file to be downloaded. |
headers | IHeaders | No | Key, value pairs of HTTP headers to send along with the request. Used when the target file is protected by a password or if any |
Return value
A promise that resolves when the file is downloaded successfully.
Possible errors
- Error If
filePathis not a valid object or does not containstorageUnitandfilePath. - Error If
sourceUriis not a valid URI. - Error If
headersis not a valid object. - Error If the parent directory of
filePathdoes not exist. - Error If the network request fails.
Example
const filePath = {
storageUnit: internalStorageUnit,
filePath: 'path/to/downloaded/file.zip',
};
const sourceUri = 'https://example.com/path/to/file.zip';
const headers = {
'Authorization': 'Bearer your_token_here',
};
await sos.fileSystem.downloadFile(filePath, sourceUri, headers);
exists()
The exists() method checks whether a file or directory exists.
exists(filePath: IFilePath): Promise<boolean>;
Params
| Name | Type | Required | Description |
|---|---|---|---|
filePath | IFilePath | Yes | The path to the file or directory to check. |
Return value
A promise that resolves to true if the file or directory exists, false otherwise.
Possible errors
- Error If the
filePathis not a valid object or does not containstorageUnitandfilePath. - Error If any error occurs during the existence check operation on the device.
Example
const filePath = {
storageUnit: internalStorageUnit,
filePath: 'path/to/file.txt',
};
const fileExists = await sos.fileSystem.exists(filePath);
console.log(`File exists: ${fileExists}`); // Prints true if the file exists, false otherwise
extractFile()
The extractFile() method extract (recursively) the archive file at archiveFilePath into a new file specified by destinationDirectoryPath.
- The directory/folder you are extracting your ZIP file into has to be created BEFORE you start extracting the ZIP.
- Only supported extract method is
zip.
extractFile(archiveFilePath: IFilePath, destinationDirectoryPath: IFilePath, method: ExtractMethodType): Promise<void>;
Params
| Name | Type | Required | Description |
|---|---|---|---|
archiveFilePath | IFilePath | Yes | The path to the archive file to be decompressed. |
destinationDirectoryPath | IFilePath | Yes | The path to the directory where the decompressed files will be saved. |
method | ExtractMethodType | Yes | Extract method to use for extracting, e.g. 'zip'. |
Possible errors
- Error If the archive file path does not exist.
- Error If it is not a valid archive file.
- Error If destination directory does not exist.
Example
const archiveFilePath = {
storageUnit: internalStorageUnit,
filePath: 'path/to/archive.zip',
};
const destinationDirectoryPath = {
storageUnit: internalStorageUnit,
filePath: 'path/to/destination/directory',
};
await sos.fileSystem.extractFile(archiveFilePath, destinationDirectoryPath, 'zip');
getFile()
The getFile() method returns runtime information about a file path, such as local url, last modified date or size.
Return statement is a dynamic object! It has to be always generated and retrieved by this JS API, as the values in localUri differ platform by platform. Never generate the object manually. {"localUri":"file://internal/path/to/file.txt"} is for demonstration only.
getFile(filePath: IFilePath): Promise<IFile | null>;
Params
| Name | Type | Required | Description |
|---|---|---|---|
filePath | IFilePath | Yes | The path to the file to be retrieved. |
Return value
A promise that resolves to the file information or null if the file does not exist.
Possible errors
- Error If the
filePathis not a valid object or does not containstorageUnitandfilePath. - Error If the file is a directory.
- Error If any error occurs during the retrieval operation on the device.
Example
// Get file information
const filePath = {
storageUnit: internalStorageUnit,
filePath: 'path/to/file.txt',
};
const fileInfo = await sos.fileSystem.getFile(filePath);
console.log(JSON.stringify(fileInfo)); // Prints the file information
console.log(fileInfo.localUri); // Prints the local URI of the file
getFileChecksum()
The getChecksumFile() method computes a checksum of the file specified by filePath.
If you are about to use the MD5 file validation it will automatically return on any Samsung Tizen - 2.4, 3.0 and 4.0. Reason: MD5 file checksum is not available on any Tizen displays due to the Samsung restriction.
getFileChecksum(filePath: IFilePath, hashType: HashAlgorithm): Promise<string>;
Params
| Name | Type | Required | Description |
|---|---|---|---|
filePath | IFilePath | Yes | The path to the file for which the checksum will be computed. |
hashType | HashAlgorithm | Yes | The type of hash algorithm to use for computing the checksum. |
Return value
A promise that resolves to the computed checksum of the file.
Possible errors
- Error If
filePathis not a valid object or does not containstorageUnitandfilePath. - Error If
hashTypeis not a valid type or string. - Error If the file does not exist.
- Error If
filepathit is a directory
Example
const filePath = {
storageUnit: internalStorageUnit,
filePath: 'path/to/file.txt',
};
const checksum = await sos.fileSystem.getFileChecksum(filePath, 'md5');
console.log(`Checksum of the file: ${checksum}`);
isDirectory()
The isDirectory() method checks whether the file path points to a directory.
isDirectory(filePath: IFilePath): Promise<boolean>;
Params
| Name | Type | Required | Description |
|---|---|---|---|
filePath | IFilePath | Yes | The file path to check. |
Return value
A promise that resolves to true if the file path is a directory, false otherwise.
Possible errors
- Error If
filePathis not a valid object or does not containstorageUnitandfilePath. - Error If the file path does not exist.
Example
const filePath = {
storageUnit: internalStorageUnit,
filePath: 'path/to/directory',
};
const isDir = await sos.fileSystem.isDirectory(filePath);
if (isDir) {
console.log('The file path is a directory.');
} else {
console.log('The file path is not a directory.');
}
link()
The link() method creates a symbolic link from sourceFilePath (existing path) to destinationFilePath (new path).
This method is only available on Linux devices.
link(sourceFilePath: IFilePath, destinationFilePath: IFilePath): Promise<void>;
Params
| Name | Type | Required | Description |
|---|---|---|---|
sourceFilePath | IFilePath | Yes | The path to the existing file or directory that you want to link to. |
destinationFilePath | IFilePath | Yes | The path where the symbolic link will be created. |
Return value
A promise that resolves when the symbolic link is created successfully.
Possible errors
- Error If
sourceFilePathordestinationPathis not a valid object or does not containstorageUnitandfilePath. - Error If the
sourceFilePathdoes not exist or if thedestinationFilePathalready exists. - Error The platform does not support linking directories.
Example
const internalStorageUnit = (await sos.fileSystem.listInternalStorageUnits())[0];
const sourceFilePath = {
storageUnit: internalStorageUnit,
filePath: 'path/to/existing/file.txt',
};
const destinationFilePath = {
storageUnit: internalStorageUnit,
filePath: 'path/to/symlink/file_link.txt',
};
await sos.fileSystem.link(sourceFilePath, destinationFilePath);
listFiles()
The listFiles() method lists all files and directories in the specified path (nested files are not included).
listFiles(directoryPath: IFilePath): Promise<IFilePath[]>;
Params
| Name | Type | Required | Description |
|---|---|---|---|
directoryPath | IFilePath | Yes | The path to the directory where files will be listed. |
Return value
A promise that resolves to an array of file paths in the specified directory.
Possible errors
- Error If
directoryPathis not a valid object or does not containstorageUnitandfilePath. - Error If the path does not exist, or it is a file.
Example
// List files in the root directory of the internal storage unit
const internalStorageUnit = (await sos.fileSystem.listInternalStorageUnits())[0];
const directoryPath = {
storageUnit: internalStorageUnit,
filePath: '', // Empty string is used as an absolute path instead of "/"
};
const files = await sos.fileSystem.listFiles(directoryPath);
console.log('Files in the root directory:', files.length);
files.forEach((file) => {
console.log(`File: ${file.filePath}`);
});
listInternalStorageUnits()
A shorthand method for listing only the internal storage units (i.e., those with the removable: false). The capacity values are in bytes.
listInternalStorageUnits(): Promise<IStorageUnit[]>;
Return value
An array of internal storage units available on the device.
Example
// List internal storage units
const internalStorageUnits = await sos.fileSystem.listInternalStorageUnits();
internalStorageUnits.forEach((storageUnit) => {
console.log(`Storage Unit Type: ${storageUnit.type}`);
console.log(`Capacity: ${storageUnit.capacity} bytes`);
console.log(`Free Space: ${storageUnit.freeSpace} bytes`);
console.log(`Usable Space: ${storageUnit.usableSpace} bytes`);
});
listStorageUnits()
The listStorageUnits() method lists all available storage units. All devices always have one internal storage device (with
removable: false) and zero or more external devices. The capacity values are in bytes.
This is a mandatory method that is required for all the other File System APIs. The other APIs require a storageUnit object that is retrieved from this method to manipulate with files on a correct storage location (internal/external).
storageUnit is a dynamic object! It has to be always generated and retrieved by this JS API, as the values in type differ platform by platform. Never generate the object manually. {"type":"internal"} is for demonstration only.
listStorageUnits(): Promise<IStorageUnit[]>;
Return value
An array of storage units available on the device.
Possible errors
InternalFileSystemError Unexpected error occurred when listing storage units.
Example
// Storage units are equivalent to disk volumes (C:, D: etc on Windows; /mnt/disc1, /mnt/disc2 on Unix)
const storageUnits = await sos.fileSystem.listStorageUnits();
const externalStorageUnits = storageUnits.filter((storageUnit) => storageUnit.removable);
externalStorageUnits.forEach((storageUnit) => {
console.log(`Storage Unit Type: ${storageUnit.type}`);
console.log(`Capacity: ${storageUnit.capacity} bytes`);
});
moveFile()
The moveFile() method moves a file from sourceFilePath to destinationFilePath.
moveFile(sourceFilePath: IFilePath, destinationFilePath: IFilePath, options?: IMoveFileOptions): Promise<void>;
Params
| Name | Type | Required | Description |
|---|---|---|---|
sourceFilePath | IFilePath | Yes | The path to the file to be moved. |
destinationFilePath | IFilePath | Yes | The path where the file will be moved to. |
options | IMoveFileOptions | No | Options for moving the file. |
options.overwrite | boolean | No | If set to true, the method will overwrite the destination file if it already exists. |
Return value
A promise that resolves when the file is moved successfully.
Possible errors
- Error If the source file does not exist or parent of the destination file path does not exist.
- Error If the
options.overwriteis not set and the destination file path already exists. - Error If deleting path does not exist.
- Error If any error occurs during the move operation on the device.
Example
// Move file from one directory to another and overwrite it if it already exists
const sourceFilePath = {
storageUnit: internalStorageUnit,
filePath: 'path/to/source/file.txt',
};
const destinationFilePath = {
storageUnit: internalStorageUnit,
filePath: 'path/to/destination/file.txt',
};
await sos.fileSystem.moveFile(sourceFilePath, destinationFilePath, { overwrite: true });
onStorageUnitsChanged()
The onStorageUnitsChanged() method sets up a listener, which is called whenever the list of storage units changes.
onStorageUnitsChanged(listener: () => void): void;
Params
| Name | Type | Required | Description |
|---|---|---|---|
listener | () => void | Yes | The listener function to be called when the storage units change. |
Possible errors
Error If listener is not a valid function.
readFile()
The readFile() method returns content of the file specified by filePath.
The file has to be a text file, otherwise the content will be mangled.
readFile(filePath: IFilePath): Promise<string>;
Params
| Name | Type | Required | Description |
|---|---|---|---|
filePath | IFilePath | Yes | The path to the file to be read. |
Return value
A promise that resolves to the content of the file.
Possible errors
- Error If the file does not exist.
- Error If the
filePathis not a valid object or does not containstorageUnitandfilePath. - Error If the file is a directory.
- Error If any error occurs during the read operation on the device.
Example
const filePath = {
storageUnit: internalStorageUnit,
filePath: 'path/to/file.txt',
};
const fileContent = await sos.fileSystem.readFile(filePath);
console.log(`Content of the file: ${fileContent}`);
removeAllListeners()
The removeAllListeners() method removes all listeners, previously added by onStorageUnitsChanged()
removeAllListeners(): void;
removeStorageUnitsChangedListener()
The removeStorageUnitsChangedListener() method removes a listener, previously added by onStorageUnitsChanged()
removeStorageUnitsChangedListener(listener: () => void): void;
wipeout()
The wipeout() method is used to wipe out all data from the file system.
- Ensure that function is called only once, otherwise it will wipe out the file system again on applet or device start!
- This function is clearing internal file system storage, cache storage and cookies. Local storage will not be cleared.
wipeout(): Promise<void>;
Return value
A promise that resolves when the wipeout is complete.