菜单
开源 RSS

文件

File 类表示一个文件,包含读取、定位和获取文件统计信息的方法。它由 open 函数返回。

属性

属性类型描述
pathstring文件的绝对路径。

方法

方法描述
read从文件中读取最多 buffer.byteLength 个字节到传入的 buffer 中。返回一个解析为读取字节数的 promise。
seek将文件的文件位置指示器设置为传入的 offset 字节。返回一个解析为新偏移量的 promise。
stat返回一个解析为 FileInfo 对象的 promise,其中包含有关文件的信息。

示例

JavaScript
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);

  // 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);

  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;
    }
  }

  // Check that we read the expected number of bytes
  if (totalBytesRead != fileinfo.size) {
    throw new Error('Unexpected number of bytes read');
  }
}