Skip to main content
Version: 8.10.0

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.

Device File System Capabilities
CapabilityDescription
FILE_SYSTEM_INTERNAL_STORAGEIf device supports internal storage units
FILE_SYSTEM_EXTERNAL_STORAGEIf device supports connecting external storage units
FILE_SYSTEM_FILE_CHECKSUMIf device supports checksum for MD5 or CRC32 hash algorithms
FILE_SYSTEM_LINKIf device supports creating hard links to files
FILE_SYSTEM_CREATE_ARCHIVEIf device supports creating archives - zip
FILE_SYSTEM_ARCHIVE_EXTRACT_INFOIf device supports extracting information about archive files
FILE_SYSTEM_BINARYIf device supports writing, appending and reading binary data (writeFileBytes(), appendFileBytes(), readFileBytes(), createWriteStream())
FILE_SYSTEM_RANDOM_ACCESSIf device supports writing and reading binary data at a byte position (position and length options)

If you want to check if the device supports this capability, use sos.display.supports().

Core apps released before FILE_SYSTEM_BINARY and FILE_SYSTEM_RANDOM_ACCESS existed reject sos.display.supports() for them with the DISPLAY_CAPABILITY_INVALID (41601) error code instead of resolving false, and reject the binary methods with an unknown message error. Treat both as not supported.

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. To append binary data, use appendFileBytes().

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

Params​

NameTypeRequiredDescription
filePathIFilePath
Yes
The path to the file to be appended.
contentsstring
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 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);

appendFileBytes()​

The appendFileBytes() method appends binary data to the file specified by filePath. If the file does not exist, it is created.

note

Requires the FILE_SYSTEM_BINARY capability. Check it with sos.display.supports(). On devices without it, the method rejects with the FILE_SYSTEM_BINARY_NOT_SUPPORTED (50520) error code.

appendFileBytes(filePath: IFilePath, data: Uint8Array | ArrayBuffer): Promise<void>;

Params​

NameTypeRequiredDescription
filePathIFilePath
Yes
The path to the file to be appended.
dataArrayBuffer | Uint8Array<ArrayBufferLike>
Yes
The binary data to be appended.

Return value​

A promise that resolves when the data is appended.

Possible errors​

  • Error If the device does not support binary files.
  • 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​

await sos.fileSystem.appendFileBytes(filePath, new Uint8Array([0x00, 0xff]));

copyFile()​

The copyFile() method creates a copy of file from sourceFilePath to destinationFilePath.

copyFile(sourceFilePath: IFilePath, destinationFilePath: IFilePath, options?: ICopyFileOptions): Promise<void>;

Params​

NameTypeRequiredDescription
sourceFilePathIFilePath
Yes
The path to the file to be copied.
destinationFilePathIFilePath
Yes
The path where the file will be copied to.
optionsICopyFileOptions
No
Options for copying the file.
options.overwriteboolean | undefined
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 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​

NameTypeRequiredDescription
archiveFilePathIFilePath
Yes
The path where the archive file will be created.
archiveEntriesIFilePath[]
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 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​

NameTypeRequiredDescription
directoryPathIFilePath
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 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);

createWriteStream()​

The createWriteStream() method returns a stream that writes binary chunks to the file specified by filePath one after another. The file is truncated on the first write, or on close() when nothing was written, unless options.append is set. Chunks are written in the order of the write() calls even when they are not awaited, but awaiting each write() is the only backpressure: chunks that are not awaited are kept in memory until they are written. Once a chunk fails, every following write() and close() rejects with the same error, so a write() that is not awaited rejects unhandled.

note

Requires the FILE_SYSTEM_BINARY capability. Check it with sos.display.supports(). On devices without it, write() and close() reject with the FILE_SYSTEM_BINARY_NOT_SUPPORTED (50520) error code.

createWriteStream(filePath: IFilePath, options?: ICreateWriteStreamOptions): IFileWriteStream;

Params​

NameTypeRequiredDescription
filePathIFilePath
Yes
The path to the file to be written.
optionsICreateWriteStreamOptions
No
Options for the stream.
options.appendboolean | undefined
No
Append to the existing file instead of truncating it.

Return value​

The stream with write() and close() methods.

Possible errors​

Error If the filePath is not a valid object or does not contain storageUnit and filePath.

Example​

const stream = sos.fileSystem.createWriteStream(filePath);
for (const chunk of chunks) {
await stream.write(chunk);
}
await stream.close();

deleteFile()​

The deleteFile() method deletes the file specified by filePath.

deleteFile(filePath: IFilePath, recursive: boolean): Promise<void>;

Params​

NameTypeRequiredDescription
filePathIFilePath
Yes
The path to the file or directory to be deleted.
recursiveboolean
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 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​

NameTypeRequiredDescription
filePathIFilePath
Yes
The path where the downloaded file will be saved.
sourceUristring
Yes
The URI of the file to be downloaded.
headersIHeaders
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 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​

NameTypeRequiredDescription
filePathIFilePath
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 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​

NameTypeRequiredDescription
archiveFilePathIFilePath
Yes
The path to the archive file to be decompressed.
destinationDirectoryPathIFilePath
Yes
The path to the directory where the decompressed files will be saved.
methodExtractMethodType
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.

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​

NameTypeRequiredDescription
filePathIFilePath
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 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​

NameTypeRequiredDescription
filePathIFilePath
Yes
The path to the file for which the checksum will be computed.
hashTypeHashAlgorithm
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 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​

NameTypeRequiredDescription
filePathIFilePath
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 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​

NameTypeRequiredDescription
sourceFilePathIFilePath
Yes
The path to the existing file or directory that you want to link to.
destinationFilePathIFilePath
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 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​

NameTypeRequiredDescription
directoryPathIFilePath
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 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​

NameTypeRequiredDescription
sourceFilePathIFilePath
Yes
The path to the file to be moved.
destinationFilePathIFilePath
Yes
The path where the file will be moved to.
optionsIMoveFileOptions
No
Options for moving the file.
options.overwriteboolean | undefined
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.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​

NameTypeRequiredDescription
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. To read binary data, use readFileBytes().

readFile(filePath: IFilePath): Promise<string>;

Params​

NameTypeRequiredDescription
filePathIFilePath
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 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}`);

readFileBytes()​

The readFileBytes() method returns the binary content of the file specified by filePath, or a part of it with options.position and options.length.

note

Requires the FILE_SYSTEM_BINARY capability, options.position and options.length also FILE_SYSTEM_RANDOM_ACCESS. Check them with sos.display.supports(). On devices without them, the method rejects with the FILE_SYSTEM_BINARY_NOT_SUPPORTED (50520) or FILE_SYSTEM_RANDOM_ACCESS_NOT_SUPPORTED (50521) error code.

readFileBytes(filePath: IFilePath, options?: IReadFileBytesOptions): Promise<Uint8Array>;

Params​

NameTypeRequiredDescription
filePathIFilePath
Yes
The path to the file to be read.
optionsIReadFileBytesOptions
No
Options for reading the file.
options.positionnumber | undefined
No
Byte to start reading from, defaults to 0.
options.lengthnumber | undefined
No
Number of bytes to read, defaults to the rest of the file. Fewer bytes are returned at the end of the file.

Return value​

A promise that resolves to the content of the file.

Possible errors​

  • Error If the device does not support binary files or random access.
  • Error If the filePath is not a valid object or does not contain storageUnit and filePath.
  • Error If options.position or options.length is not a non-negative number.
  • Error If the device returns something other than binary data.
  • Error If the file does not exist or is a directory.
  • Error If any error occurs during the read operation on the device.

Example​

const bytes = await sos.fileSystem.readFileBytes(filePath);

// Read a large file in 64 KB chunks
const file = await sos.fileSystem.getFile(filePath);
for (let position = 0; position < file.sizeBytes; position += 65536) {
const chunk = await sos.fileSystem.readFileBytes(filePath, { position, length: 65536 });
processChunk(chunk);
}

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.

danger
  • 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.

Example​

await sos.fileSystem.wipeout().then(() => {
console.log('File system wiped out successfully.');
await sos.management.power.systemReboot(); // Reboot the device after wipeout
}).catch((error) => {
console.error('Error wiping out file system:', error);
});

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​

NameTypeRequiredDescription
filePathIFilePath
Yes
The path to the file to be written.
contentsstring
Yes
The 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);

writeFileBytes()​

The writeFileBytes() method writes binary data to the file specified by filePath. If the file does not exist, it is created. Without options.position, the file is truncated first, like writeFile(). With options.position, the data overwrites the file in place starting at that byte and the rest of the file is kept.

note

Requires the FILE_SYSTEM_BINARY capability, options.position also FILE_SYSTEM_RANDOM_ACCESS. Check them with sos.display.supports(). On devices without them, the method rejects with the FILE_SYSTEM_BINARY_NOT_SUPPORTED (50520) or FILE_SYSTEM_RANDOM_ACCESS_NOT_SUPPORTED (50521) error code.

writeFileBytes(filePath: IFilePath, data: Uint8Array | ArrayBuffer, options?: IWriteFileBytesOptions): Promise<void>;

Params​

NameTypeRequiredDescription
filePathIFilePath
Yes
The path to the file to be written.
dataArrayBuffer | Uint8Array<ArrayBufferLike>
Yes
The binary data to be written.
optionsIWriteFileBytesOptions
No
Options for writing the data.
options.positionnumber | undefined
No
Byte to start writing at without truncating the file. Must not be greater than the file size.

Return value​

A promise that resolves when the data is written.

Possible errors​

  • Error If the device does not support binary files or random access.
  • Error If the filePath is not a valid object or does not contain storageUnit and filePath.
  • Error If options.position is not a non-negative number.
  • Error If the parent directory does not exist or the filePath is a directory.
  • Error If any error occurs during the write operation on the device.

Example​

// To save a remote file, use downloadFile(), which does not load the file into applet memory
if (await sos.display.supports('FILE_SYSTEM_BINARY').catch(() => false)) {
await sos.fileSystem.writeFileBytes(filePath, new Uint8Array([0x89, 0x50, 0x4e, 0x47]));
}

// Overwrite 4 bytes at byte 1024
await sos.fileSystem.writeFileBytes(filePath, new Uint8Array([1, 2, 3, 4]), { position: 1024 });

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);
}

// write and read binary data, if the device supports it
// (core apps without the capability reject supports() instead of resolving false)
if (await sos.display.supports('FILE_SYSTEM_BINARY').catch(() => false)) {
const binaryPath = fpath.join(root, 'data.bin');
const bytes = new Uint8Array(1024 * 1024).map((_, index) => index % 256);

// write large data in chunks, so only one chunk is sent to the device at a time
const stream = sos.fileSystem.createWriteStream(binaryPath);
for (let offset = 0; offset < bytes.length; offset += 64 * 1024) {
await stream.write(bytes.subarray(offset, offset + 64 * 1024));
}
await stream.close();

// read the whole file, or only a part of it when random access is supported
const all = await sos.fileSystem.readFileBytes(binaryPath);
console.log(`read ${all.length} bytes`);
if (await sos.display.supports('FILE_SYSTEM_RANDOM_ACCESS').catch(() => false)) {
const header = await sos.fileSystem.readFileBytes(binaryPath, { position: 0, length: 16 });
console.log('first 16 bytes', Array.from(header));
}
}
});