Documentation for automated readers
A curated documentation index is available at: https://grafana.com/llms.txt
A complete documentation index is available at: https://grafana.com/llms-full.txt
These indexes can help with page discovery before fetching individual documents.
This page is also available in Markdown, which may be easier for automated readers and AI tools to parse than HTML. The Markdown version is available at https://grafana.com/docs/k6/next/javascript-api/k6-experimental/fs/file/read.md, or by sending Accept: text/markdown to https://grafana.com/docs/k6/next/javascript-api/k6-experimental/fs/file/read/. For broader documentation discovery, the curated index is available at https://grafana.com/llms.txt and the complete index is available at https://grafana.com/llms-full.txt.
This is documentation for the next version of Grafana k6 documentation. For the latest stable release, go to the latest version.
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

