fs
注意
这是一个实验性模块。
虽然我们力求保持实验性模块的稳定性,但可能需要引入重大更改。这种情况可能在未来的 k6 发布版本中发生,直到该模块完全稳定并作为 k6 核心模块“毕业”。有关更多信息,请参阅扩展毕业流程。
实验性模块保持了高水平的稳定性,并遵循常规维护和安全措施。如果您有任何反馈或建议,请随时提出 Issue。
k6 filesystem 实验性模块提供了一种内存高效的方式来处理测试脚本中的文件交互。它目前支持打开文件、读取其内容、在其内容中查找以及检索有关文件的元数据。
内存效率
文件系统模块的关键优势之一是其内存效率。与传统的 open 函数不同,传统方法会将文件多次加载到内存中,而文件系统模块通过尽可能少地加载文件并在所有 VU 之间共享相同的内存空间来减少内存使用。这种方法降低了内存不足错误的风险,尤其是在涉及大文件的负载测试中。
使用注意事项
使用文件系统模块时一个重要的注意事项是它如何处理外部文件修改。k6 加载文件后,它就像是文件内容的“视图”。如果在测试期间修改底层文件,k6 不会在已加载的 File 实例中反映这些更改。
API 概览
该模块导出了用于与文件系统交互的函数和对象
函数/对象 | 描述 |
---|---|
open | 打开一个文件并返回一个解析为 File 实例的 Promise。 |
文件 | 表示一个文件,包含用于读取、查找和获取文件统计信息的方法。 |
SeekMode | 一个枚举,用于指定查找操作的参考点。包括 Start 、Current 和 End 。 |
示例
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');
}
}