FileSystemSyncAccessHandle.getSize()

Baseline 2023
Newly available

Since March 2023, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

安全なコンテキスト用: この機能は一部またはすべての対応しているブラウザーにおいて、安全なコンテキスト (HTTPS) でのみ利用できます。

FileSystemSyncAccessHandle インターフェイスの getSize() メソッドは、ハンドルに対応するファイルのサイズをバイト単位で返します。

構文

js
getSize()

引数

なし

返値

ファイルのバイト数を表す数値で解決する Promise を返します。

例外

InvalidStateError DOMException

対応するアクセスハンドルが既に閉じられているとき投げられます。

以下の非同期のイベントハンドラー関数は、Web Worker の中にあります。メインスレッドからメッセージを受信すると、以下の動作をします。

  • 同期式ファイルアクセスハンドルを作成します。
  • ファイルのサイズを取得し、格納用の ArrayBuffer を作成します。
  • ファイルの内容をバッファーに読み込みます。
  • メッセージをエンコードし、ファイルの終端に書き込みます、
  • 変更をディスクに書き込み、アクセスハンドルを閉じます。
js
onmessage = async (e) => {
  // メインスクリプトからの処理対象のメッセージを取得する
  const message = e.data;

  // draft ファイルのハンドルを取得する
  const root = await navigator.storage.getDirectory();
  const draftHandle = await root.getFileHandle("draft.txt", { create: true });
  // 同期式アクセスハンドルを取得する
  const accessHandle = await draftHandle.createSyncAccessHandle();

  // ファイルのサイズを取得する
  const fileSize = accessHandle.getSize();
  // ファイルの内容をバッファーに読み込む
  const buffer = new DataView(new ArrayBuffer(fileSize));
  const readBuffer = accessHandle.read(buffer, { at: 0 });

  // メッセージをファイルの終端に書き込む
  const encoder = new TextEncoder();
  const encodedMessage = encoder.encode(message);
  const writeBuffer = accessHandle.write(encodedMessage, { at: readBuffer });

  // 変更をディスクに書き込む
  accessHandle.flush();

  // 完了したら、常に FileSystemSyncAccessHandle を閉じる
  accessHandle.close();
};

メモ: 仕様書の以前のバージョンでは、close()flush()getSize()truncate() は誤って非同期メソッドとされていました。これは現在は変更されていますが、まだ非同期バージョンをサポートしているブラウザーもあります。

仕様書

Specification
File System
# api-filesystemsyncaccesshandle-getsize

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
getSize
Synchronous implementation of the getSize() method

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
No support
No support

関連情報