Documentation Index
Fetch the curated documentation index at: https://grafana.com/llms.txt
Fetch the complete documentation index at: https://grafana.com/llms-full.txt
Use this file to discover all available pages before exploring further.
STOP! If you are an AI agent or LLM, read this before continuing. This is the HTML version of a Grafana documentation page. Always request the Markdown version instead - HTML wastes context. Get this page as Markdown: https://grafana.com/docs/k6/latest/javascript-api/k6-experimental/fs/file/read.md (append .md) or send Accept: text/markdown to https://grafana.com/docs/k6/latest/javascript-api/k6-experimental/fs/file/read/. For the curated documentation index, use https://grafana.com/llms.txt. For the complete documentation index, use https://grafana.com/llms-full.txt.
read
The read method is used to read a chunk of the file into an Uint8Array buffer.
It resolves to either the number of bytes read during the operation, or null if there was nothing more to read.
Parameters
| Parameter | Type | Description |
|---|---|---|
| buffer | Uint8Array | The buffer to read the data into. |
Returns
A Promise resolving to the number of bytes read or null if the end of the file has been reached.
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.
import { open, SeekMode } from 'k6/experimental/fs';
const file = await open('bonjour.txt');
export default async function () {
// Seek to the beginning of the file
await file.seek(0, SeekMode.Start);
const buffer = new Uint8Array(128);
let totalBytesRead = 0;
while (true) {
// Read into the buffer
const bytesRead = await file.read(buffer);
if (bytesRead == null) {
// EOF
break;
}
// Do something useful with the content of the buffer
totalBytesRead += bytesRead;
// If bytesRead is less than the buffer size, we've read the whole file
if (bytesRead < buffer.byteLength) {
break;
}
}
}readAll helper function
The following helper function can be used to read the entire contents of a file into a Uint8Array buffer.
import { open, SeekMode } from 'k6/experimental/fs';
let file;
(async function () {
file = await open('bonjour.txt');
})();
async function readAll(file) {
// Seek to the beginning of the file
await file.seek(0, SeekMode.Start);
const fileInfo = await file.stat();
const buffer = new Uint8Array(fileInfo.size);
const bytesRead = await file.read(buffer);
if (bytesRead !== fileInfo.size) {
throw new Error(
'unexpected number of bytes read; expected ' +
fileInfo.size +
' but got ' +
bytesRead +
' bytes'
);
}
return buffer;
}
export default async function () {
// Read the whole file
const fileContent = await readAll(file);
console.log(JSON.stringify(fileContent));
}Was this page helpful?
Related resources from Grafana Labs

