read
read
方法用于将文件的块内容读取到 Uint8Array 缓冲区。
它返回读取操作期间读取的字节数,如果文件已读完,则返回 null
。
参数
参数 | 类型 | 描述 |
---|---|---|
buffer | Uint8Array | 用于读取数据的缓冲区。 |
返回值
一个 Promise,解析为读取的字节数,如果已到达文件末尾,则为 null
。
示例
读取文件
在以下示例中,我们打开一个文件,并以 128 字节为块分批读取,直到文件末尾。
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
辅助函数
以下辅助函数可用于将文件全部内容读取到 Uint8Array 缓冲区。
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));
}