Skip to content

Commit

Permalink
Add example implementation of readAll
Browse files Browse the repository at this point in the history
  • Loading branch information
oleiade committed Nov 21, 2023
1 parent 1e28d34 commit fbbd482
Showing 1 changed file with 64 additions and 10 deletions.
74 changes: 64 additions & 10 deletions docs/sources/next/javascript-api/k6-experimental/fs/file/read.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ A [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Gl

## Example

### Reading a file

In the following example, we open a file and read it in chunks of 128 bytes until we reach the end of the file.

{{< code >}}

```javascript
Expand All @@ -33,13 +37,7 @@ let file;
})();

export default async function () {
// About information about the file
const fileinfo = await file.stat();
if (fileinfo.name != 'bonjour.txt') {
throw new Error('Unexpected file name');
}

const buffer = new Uint8Array(4);
const buffer = new Uint8Array(128);

let totalBytesRead = 0;
while (true) {
Expand All @@ -59,11 +57,67 @@ export default async function () {
}
}

// Check that we read the expected number of bytes
if (totalBytesRead != fileinfo.size) {
throw new Error('Unexpected number of bytes read');
// Seek back to the beginning of the file
await file.seek(0, SeekMode.Start);
}
```

{{< /code >}}

### `readAll` helper function

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.

{{< code >}}

```javascript
import { open, SeekMode } from 'k6/experimental/fs';

let file;
(async function () {
file = await open('bonjour.txt');
})();

async function readAll(file, bufferSize = 128) {
// Obtain the size of the file
const fileInfo = await file.stat();
const fileSize = fileInfo.size;

// Prepare a buffer to store the file content
const fileContent = new Uint8Array(fileInfo.size);
let fileOffset = 0;

// Prepare a buffer to read the chunks of the file into
const buffer = new Uint8Array(Math.min(bufferSize, fileSize));

while (true) {
// Read a chunk of the file
const bytesRead = await file.read(buffer);
if (bytesRead == null || bytesRead === 0) {
// EOF
break;
}

// Copy the content of the buffer into the file content buffer
fileContent.set(buffer.slice(0, bytesRead), fileOffset);

// Do something useful with the content of the buffer
fileOffset += bytesRead;

// If bytesRead is less than the buffer size, we've read the whole file
if (bytesRead < buffer.byteLength) {
break;
}
}

return fileContent;
}

export default async function () {
// Read the whole file
const fileContent = await readAll(file);
console.log(JSON.stringify(fileContent));

// Seek back to the beginning of the file
await file.seek(0, SeekMode.Start);
}
Expand Down

0 comments on commit fbbd482

Please sign in to comment.