FileSystemFileHandle: createWritable() method

Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

Note: This feature is available in Web Workers.

The createWritable() method of the FileSystemFileHandle interface creates a FileSystemWritableFileStream that can be used to write to a file. The method returns a Promise which resolves to this created stream.

Any changes made through the stream won't be reflected in the file represented by the file handle until the stream has been closed. This is typically implemented by writing data to a temporary file, and only replacing the file represented by file handle with the temporary file when the writable filestream is closed.

Syntax

js
createWritable()
createWritable(options)

Parameters

options Optional

An object with the following properties:

keepExistingData Optional

A Boolean. Default false. When set to true if the file exists, the existing file is first copied to the temporary file. Otherwise the temporary file starts out empty.

Return value

A Promise which resolves to a FileSystemWritableFileStream object.

Exceptions

NotAllowedError DOMException

Thrown if the PermissionStatus.state for the handle is not 'granted' in readwrite mode.

NotFoundError DOMException

Thrown if current entry is not found.

NoModificationAllowedError DOMException

Thrown if the browser is not able to acquire a lock on the file associated with the file handle.

AbortError DOMException

Thrown if implementation-defined malware scans and safe-browsing checks fails.

Examples

The following asynchronous function writes the given contents to the file handle, and thus to disk.

js
async function writeFile(fileHandle, contents) {
  // Create a FileSystemWritableFileStream to write to.
  const writable = await fileHandle.createWritable();

  // Write the contents of the file to the stream.
  await writable.write(contents);

  // Close the file and write the contents to disk.
  await writable.close();
}

Specifications

Specification
File System Standard
# api-filesystemfilehandle-createwritable

Browser compatibility

BCD tables only load in the browser

See also