You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/sources/next/javascript-api/k6-experimental/fs/file/read.md
+64-10Lines changed: 64 additions & 10 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -22,6 +22,10 @@ A [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Gl
22
22
23
23
## Example
24
24
25
+
### Reading a file
26
+
27
+
In the following example, we open a file and read it in chunks of 128 bytes until we reach the end of the file.
28
+
25
29
{{< code >}}
26
30
27
31
```javascript
@@ -33,13 +37,7 @@ let file;
33
37
})();
34
38
35
39
exportdefaultasyncfunction () {
36
-
// About information about the file
37
-
constfileinfo=awaitfile.stat();
38
-
if (fileinfo.name!='bonjour.txt') {
39
-
thrownewError('Unexpected file name');
40
-
}
41
-
42
-
constbuffer=newUint8Array(4);
40
+
constbuffer=newUint8Array(128);
43
41
44
42
let totalBytesRead =0;
45
43
while (true) {
@@ -59,11 +57,67 @@ export default async function () {
59
57
}
60
58
}
61
59
62
-
// Check that we read the expected number of bytes
63
-
if (totalBytesRead !=fileinfo.size) {
64
-
thrownewError('Unexpected number of bytes read');
60
+
// Seek back to the beginning of the file
61
+
awaitfile.seek(0, SeekMode.Start);
62
+
}
63
+
```
64
+
65
+
{{< /code >}}
66
+
67
+
### `readAll` helper function
68
+
69
+
The following helper function can be used to read the entire contents of a file into a [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) buffer.
0 commit comments