Skip to main content
Version: 8.1.3

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.

Differences between File System API and Offline Cache API

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.

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.

note

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

NameTypeDescription
filePathIFilePathThe path to the file to be appended.
contentsstringThe 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 filePath is a directory.
  • Error If the filePath is not a valid object or does not contain storageUnit and filePath.
  • 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

NameTypeDescription
sourceFilePathIFilePathThe path to the file to be copied.
destinationFilePathIFilePathThe path where the file will be copied to.
options (optional)ICopyFileOptionsOptions for copying the file.
options.overwrite (optional)booleanIf 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 options object 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.

warning
  • Never start OR end the filePath with a slash - /.
  • It is a good practice to check if file exists - exists() prior creating it
info
  • 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

NameTypeDescription
archiveFilePathIFilePathThe path where the archive file will be created.
archiveEntriesIFilePath[]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 archiveFilePath is not a valid object or does not contain storageUnit and filePath.
  • Error If archiveEntries is not a valid array of objects.
  • Error If the parent directory of archiveFilePath does not exist.
  • Error If any of the archiveEntries do 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.

warning
  • 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

NameTypeDescription
directoryPathIFilePathThe path where the new directory will be created.

Return value

A promise that resolves when the directory is created successfully.

Possible errors

  • Error If directoryPath is not a valid object or does not contain storageUnit and filePath.
  • 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

NameTypeDescription
filePathIFilePathThe path to the file or directory to be deleted.
recursivebooleanIf 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 filePath is not a valid object or does not contain storageUnit and filePath.
  • Error If the file does not exist or if recursive is 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.

danger

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

NameTypeDescription
filePathIFilePathThe path where the downloaded file will be saved.
sourceUristringThe URI of the file to be downloaded.
headers (optional)IHeadersKey, 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 filePath is not a valid object or does not contain storageUnit and filePath.
  • Error If sourceUri is not a valid URI.
  • Error If headers is not a valid object.
  • Error If the parent directory of filePath does 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

NameTypeDescription
filePathIFilePathThe 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 filePath is not a valid object or does not contain storageUnit and filePath.
  • 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.

note
  • 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

NameTypeDescription
archiveFilePathIFilePathThe path to the archive file to be decompressed.
destinationDirectoryPathIFilePathThe path to the directory where the decompressed files will be saved.
methodExtractMethodTypeExtract 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.

warning

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

NameTypeDescription
filePathIFilePathThe 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 filePath is not a valid object or does not contain storageUnit and filePath.
  • 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.

Tizen limitation

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

NameTypeDescription
filePathIFilePathThe path to the file for which the checksum will be computed.
hashTypeHashAlgorithmThe 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 filePath is not a valid object or does not contain storageUnit and filePath.
  • Error If hashType is not a valid type or string.
  • Error If the file does not exist.
  • Error If filepath it 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

NameTypeDescription
filePathIFilePathThe 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 filePath is not a valid object or does not contain storageUnit and filePath.
  • 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.');
}

The link() method creates a symbolic link from sourceFilePath (existing path) to destinationFilePath (new path).

note

This method is only available on Linux devices.

link(sourceFilePath: IFilePath, destinationFilePath: IFilePath): Promise<void>;

Params

NameTypeDescription
sourceFilePathIFilePathThe path to the existing file or directory that you want to link to.
destinationFilePathIFilePathThe 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 sourceFilePath or destinationPath is not a valid object or does not contain storageUnit and filePath.
  • Error If the sourceFilePath does not exist or if the destinationFilePath already 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

NameTypeDescription
directoryPathIFilePathThe 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 directoryPath is not a valid object or does not contain storageUnit and filePath.
  • 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.

note

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).

warning

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

NameTypeDescription
sourceFilePathIFilePathThe path to the file to be moved.
destinationFilePathIFilePathThe path where the file will be moved to.
options (optional)IMoveFileOptionsOptions for moving the file.
options.overwrite (optional)booleanIf 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.overwrite is 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

NameTypeDescription
listener() => voidThe 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

NameTypeDescription
filePathIFilePathThe 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 filePath is not a valid object or does not contain storageUnit and filePath.
  • 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, later when action is finished the device is rebooted.

wipeout(): Promise<void>;

Return value

A promise that resolves when the wipeout is complete.

danger
  • Ensure that function is called only once, otherwise it will wipe out the file system again on applet start!
  • This function is clearing internal file system storage, cache storage and cookies. Local storage will not be cleared.

writeFile()

The writeFile() method writes string content to the file specified by filePath. If the file does exist, it is created.

writeFile(filePath: IFilePath, contents: string): Promise<void>;

Params

NameTypeDescription
filePathIFilePathThe path to the file to be written.
contentsstringThe content to be written to the file.

Return value

A promise that resolves when the content is written successfully.

Possible errors

  • Error If the parent directory does not exist or the filePath is a directory.
  • Error If the filePath is not a valid object or does not contain storageUnit and filePath.
  • Error If any error occurs during the write operation on the device.

Example

const filePath = {
storageUnit: internalStorageUnit,
filePath: 'path/to/file.txt',
};

const contents = 'This is the content to write to the file.';
await sos.fileSystem.writeFile(filePath, contents);

API Example

import { sos, fpath } from '@signageos/front-applet';
import { IFilePath } from '@signageos/front-applet/es6/FrontApplet/FileSystem/types';

void sos.onReady(async () => {
const [internal] = await sos.fileSystem.listInternalStorageUnits();

const root: IFilePath = {
storageUnit: internal,
filePath: '', // empty string points to root directory
};

// list files in the root directory
const contents = await sos.fileSystem.listFiles(root);

// print files from the root directory
for (const entries of contents) {
if (await sos.fileSystem.isDirectory(entries)) {
console.log(`${entries.filePath} (directory)`);
} else {
console.log(`${entries.filePath} (file)`);
}
}

// write data into a file
const writePath = fpath.join(root, 'value.json');
await sos.fileSystem.writeFile(writePath, JSON.stringify({ data: 'Lorem ipsum dolor sit amet' }));

// download a file from the internet and play it
const downloadPath = fpath.join(root, 'video.mp4');
await sos.fileSystem.downloadFile(
downloadPath,
'https://static.signageos.io/assets/test-videos-03_AME/video-test-03_15s_1920x1080_2fe7b039750a134aeac1c0a515710007.mp4',
);
const file = await sos.fileSystem.getFile(downloadPath);

if (file) {
await sos.video.prepare(file.filePath, 0, 0, 1920, 1080);
await sos.video.play(file.filePath, 0, 0, 1920, 1080);
}
});