-
Notifications
You must be signed in to change notification settings - Fork 8k
/
index.md
83 lines (57 loc) · 2.63 KB
/
index.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
---
title: FileSystemSyncAccessHandle:close() 方法
slug: Web/API/FileSystemSyncAccessHandle/close
l10n:
sourceCommit: f10fbe2d2dc4857bf29ce955689a7ba7c1ffac8b
---
{{securecontext_header}}{{APIRef("File System API")}}{{AvailableInWorkers("dedicated")}}
{{domxref("FileSystemSyncAccessHandle")}} 接口的 **`close()`** 方法用于关闭一个打开的同步文件句柄,禁止之后对其的任何操作并且释放之前加在与文件句柄相关联的文件上的独占锁。
> **备注:** 在规范早期版本中,`close()`、{{domxref("FileSystemSyncAccessHandle.flush()", "flush()")}}、{{domxref("FileSystemSyncAccessHandle.getSize()", "getSize()")}} 和 {{domxref("FileSystemSyncAccessHandle.truncate()", "truncate()")}} 被错误地规定为异步方法。某些浏览器的旧版本是依照异步方式来实现这些方法的,不过,现今所有支持这些方法的浏览器都将它们实现为同步方法。
## 语法
```js-nolint
close()
```
### 参数
无。
### 返回值
无({{jsxref('undefined')}})。
### 异常
无。
## 示例
下面的异步事件处理函数包含在一个 Web Worker 中。当收到来自主线程的消息时,它将执行:
- 创建一个同步文件访问句柄。
- 获取文件的大小然后创建一个 {{jsxref("ArrayBuffer")}} 来容纳其内容。
- 将文件内容读取到缓冲区。
- 将收到的消息编码然后写入到文件的末尾。
- 将更改保存到磁盘然后关闭访问句柄。
```js
onmessage = async (e) => {
// 接收从主线程发来的消息
const message = e.data;
// 获取草稿文件的句柄
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();
};
```
## 规范
{{Specifications}}
## 浏览器兼容性
{{Compat}}
## 参见
- [文件系统 API](/zh-CN/docs/Web/API/File_System_API)
- [文件系统访问 API:简化本地文件访问](https://developer.chrome.com/docs/capabilities/web-apis/file-system-access)